0% found this document useful (0 votes)
2 views3 pages

Sorting & Binary Search

The document contains implementations of three sorting and searching algorithms in Java: selection sort, insertion sort, and binary search. The selection sort method organizes an array by repeatedly finding the minimum element and placing it at the beginning. The insertion sort method builds a sorted array one element at a time, while the binary search method recursively finds the index of a target value in a sorted array.

Uploaded by

wrongjohann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Sorting & Binary Search

The document contains implementations of three sorting and searching algorithms in Java: selection sort, insertion sort, and binary search. The selection sort method organizes an array by repeatedly finding the minimum element and placing it at the beginning. The insertion sort method builds a sorted array one element at a time, while the binary search method recursively finds the index of a target value in a sorted array.

Uploaded by

wrongjohann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

public static void selectionSort(int[] array)

for(int index = 0; index < array.length - 1; index++)

int minIndex = index;

for(int i = index; i < array.length; i ++)

if(array[i] < array[minIndex])

minIndex = i;

int tempValue = array[index];

array[index] = array[minIndex];

array[minIndex] = tempValue;

}
public static void insertionSort(int[] array)

for(int index = 1; index < array.length; index++)

int currentIndexValue = array[index];

int sortedIndex = index - 1;

while(sortedIndex > -1 && array[sortedIndex] >


currentIndexValue)

array[sortedIndex + 1] = array[sortedIndex];

sortedIndex--;

array[sortedIndex + 1] = currentIndexValue;

}
public int binaryRec(int[] array, int target, int begin, int end) {

if (begin <= end)

int mid = (begin + end) / 2;

if (target == array[mid]) {

return mid; // Base Case

if (target < array[mid]) {

return binaryRec(array, target, begin, mid - 1);

if (target > array[mid]) {

return binaryRec(array, target, mid + 1, end);

return -1; //Alternate Base Case

You might also like