I am having issues getting my sort to check every index. It skips the 3rd indices for j
as in it goes i[0]
, j[2]
, to i[0]
, j[4]
I don't know why it is doing that?. Also, I am having trouble with my numbers actually be swapped. Does anybody know where my error is?
static void selectionSort(int[] arr) {
final long startTime = System.nanoTime(); // starts timer
System.out.println("Selection Sort");
//************** Code For Sorting *****************//
//*************************************************//
int counter = 0;
int first = 0;
int second = 0;
// Copies unsorted array to new array
//int[] sorted = Arrays.copyOf(arr, arr.length);
// sorts unsorted array for comparison later on
//Arrays.sort(sorted);
// comparing the first index value to
// the rest of the values in the array
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
// representing the next index value
// to the original and comparing it
for (int j = 1; j < arr.length - 1; j++) {
int nextIndex = j;
if (arr[minIndex] < arr[nextIndex]) {
System.out.println("i: " + i);
System.out.println("j: " + j);
System.out.println("Checking next index");
}
if (arr[minIndex] > arr[nextIndex]) {
System.out.println("i: " + i);
System.out.println("j: " + j);
//counter = j; // getting array index
first = arr[minIndex];
second = arr[nextIndex];
minIndex = second;
arr[minIndex] = second;
System.out.println("first:" + first);
System.out.println("second:" + second);
System.out.println("minIndex:" + minIndex);
System.out.println("arr[minIndex]:" + arr[minIndex]);
System.out.println("Possible lowest unsorted value");
}
//Swap here
if (arr[arr.length - 1] == arr[j]) {
arr[0] = second;
arr[counter] = first;
counter = 0;
//minIndex= i+1;
}
}
for (int k = 0; k < arr.length; k++) {
System.out.print(arr[k] + ", ");
}
System.out.println();
}
}