Lab
University
California State UniversityCourse
COMP 182 | Data Structures and Program Design and LabPages
3
Academic year
2023
KauK
Views
9
import java . util .*; public class Project1 { public static void main ( String [] args ) { Scanner stdin = new Scanner ( System . in ); //Take user input System . out . print ( "Please enter numbers separated with space (first number indicate how many numbers you will enter): " ); int arrSize = stdin . nextInt (); int [] userArr = new int [ arrSize ]; for ( int i = 0 ; i < userArr . length ; i ++) { userArr [ i ] = stdin . nextInt (); } System . out . print ( "Please enter a number you want to search: " ); int key = stdin . nextInt (); selectionSort ( userArr ); int keyIndex = binarySearch ( userArr , key ); System . out . print ( "The sorted array is: " ); for ( int i = 0 ; i < userArr . length ; i ++) System . out . print ( userArr [ i ] + (( i != userArr . length - 1 ) ? ", " : "" )); if ( keyIndex >= 0 ) System . out . println ( " \n The number " + key + " is at " + keyIndex + " index." ); else System . out . println ( "The number " + key + " is not found." ); } public static void selectionSort ( int [] arr ) { for ( int current = 0 ; current < arr . length ; current ++) { int minIndex = current ; //Check if current element is the minimum for ( int j = current + 1 ; j < arr . length ; j ++) { if ( arr [ minIndex ] > arr [ j ]) { minIndex = j ; } } //If current is not the minimum; swap with the minIndex if ( minIndex != current ) { swap ( arr , current , minIndex ); } } } public static int binarySearch ( int [] arr , int key ) { int start = 0 ; int end = arr . length - 1 ; while ( start <= end ) { //Calculate mid int mid = ( start + end ) / 2 ;
//Check if mid is equal to the key if ( arr [ mid ] == key ) return mid ; //Check if key is less than mid, ignore the right part of the array else if ( key < arr [ mid ]) end = mid - 1 ; //Else key must be greater than mid, ignore the left part of the array else start = mid + 1 ; } //-1 means not found return - 1 ; } public static void swap ( int [] arr , int i , int j ) { int temp = arr [ i ]; arr [ i ] = arr [ j ]; arr [ j ] = temp ; } }
Project 1 - Binary Search with Selection sort
Please or to post comments