Question: What is the ascending and descending order code for Selection and Insertion Sort? public static void selectionSort(double[] list) { for (int i = 0; i
What is the ascending and descending order code for Selection and Insertion Sort?
public static void selectionSort(double[] list) { for (int i = 0; i < list.length - 1; i++) { // Find the minimum in the list[i..list.length-1] double currentMin = list[i]; int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) { if (currentMin > list[j]) { currentMin = list[j]; currentMinIndex = j; } }
// Swap list[i] with list[currentMinIndex] if necessary; if (currentMinIndex != i) { list[currentMinIndex] = list[i]; list[i] = currentMin; } } } }
public static void insertionSort(double[] list) { for (int i = 1; i < list.length; i++) { /** insert list[i] into a sorted sublist list[0..i-1] so that list[0..i] is sorted. */ double currentElement = list[i]; int k; for (k = i - 1; k >= 0 && list[k] > currentElement; k--) { list[k + 1] = list[k]; }
// Insert the current element into list[k+1] list[k + 1] = currentElement; } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
