Selection Sort Algorithm Not Working
Given the following code, when I pass the array to the method selectionSort(), the array's contents are not sorted, but changed to {3, 3, 6, 6, 6, 6, 6, 6}. What is wrong with the code?
Code:
public class SortingAndSearching{
public static void main(String args[]){//Test methods
int[] list = {3,6,8,4,2,6,1};
int key = 4;
System.out.println(bruteForceSearch(list, key));
System.out.println(binarySearch(list,key));
System.exit(0);
}
//Search Methods
/**Good for small unsorted lists*/
public static int bruteForceSearch(int[] list, int key){//Slow, but easy to use.
//Also called linear search
for (int i = 0; i < list.length - 1; i++){
if (list[i] == key)
return i;
}
return -1;//If key isn't found
}
public static int binarySearch(int[] list, int key){
selectionSort(list);
int low = 0, high = list.length - 1, mid;
while(high >= low){
mid = (high + low) / 2;
if(list[mid] == key)
return mid;
else if (key > list[mid])
high = mid + 1;
else
low = mid + 1;
}
return -1;
}
public static void selectionSort(double[] list){
double currentMax = list[0];
int currentMaxIndex = 0;
for (int i = list.length - 1; i >= 1; i--){
//find maximum in list
for(int j = 1; j <= 1; j++){
if (currentMax < list[j]){
currentMax = list[j];
currentMaxIndex = j;
}
}
if(currentMaxIndex != i){
list[currentMaxIndex] = list[1];
list[i] = currentMax;
}
}
}
public static void selectionSort(int[] list){
int currentMax = list[0];
int currentMaxIndex = 0;
for (int i = list.length - 1; i >= 1; i--){
//find maximum in list
for(int j = 1; j <= 1; j++){
if (currentMax < list[j]){
currentMax = list[j];
currentMaxIndex = j;
}
}
if(currentMaxIndex != i){
list[currentMaxIndex] = list[1];
list[i] = currentMax;
}
}
for(int element: list){
System.out.println(element);
}
}
}