I'm trying to program bubble sort, selection sort and insertion sort MYSELF. However, I'm having trouble with insertion sort. I'll provide my code and what each line is doing
public void sortMethod() {
int count = 1;
for (int j = 0; j < Unsorted.length - 1; j++) {
int index = 0;
if (Unsorted[count] < Unsorted[count - 1]) {
int temp = Unsorted[count];
for (int i = count; i > 0; i--) {
if (Unsorted[i] > Unsorted[count]) {
index = i;
Unsorted[i] = Unsorted[i - 1];
}
}
Unsorted[index] = Unsorted[count];
}
count = count + 1;
}
}
Okay so int count is to figure out where the sorted array starts from. Then I declared index to find where to put the element after the sorted array and declared a temporary int for the first element of the unsorted array, if it's less than the last element of the sorted array. Then it reverses the array till the first element, and if it's greater than the element I'm adding, to assign index to its index. Essentially so I know where to place it. Then unsorted[I] = unsorted[I - 1] to shift the sorted array from where the first element of the unsorted array belongs. Then assign the first element of the unsorted array, to where it belongs. Increase the count each time
Array: 31 27 45 23 22 3 1 13 1 42
Array after sort: 27 1 1 3 22 23 1 1 1 42
BUILD SUCCESSFUL (total time: 0 seconds)