The following example demonstrates how to utilize the Selection Sort algorithm.
- You'll need to create a method called selectionSort() and pass an array.
- Loop through the array.
- Assign the current iterated i as the minimum.
- Test against other values.
- Once you find a value that's smaller, assign the current value to the minimum value.
- Test to see if the current value is different from the initial value.
- If so, swap the values for the two positions within the array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Dino Cajic | |
*/ | |
public class SelectionSort { | |
public static void main(String[] args){ | |
double[] testList = {1, 2, 3, 4, 6, 5}; | |
selectionSort(testList); | |
for (int i = 0; i < testList.length; i++){ | |
System.out.print(testList[i] + " "); | |
} | |
} | |
/** The method for sorting the numbers */ | |
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[currentMindIndex] if necessary | |
if (currentMinIndex != i) { | |
list[currentMinIndex] = list[i]; | |
list[i] = currentMin; | |
} | |
} | |
} | |
} |
Comments
Post a Comment