A little over a year ago I released an example of how to use the Bubble Sort algorithm to sort a set of data, which can be found
here.
I started my Freshman year at my University in the Fall, and for the Programming I course we're learning OOP via Java (going to be a CS Major). The sorting algorithm that we were taught was the Selection Sort method, which is more efficient than the Bubble Sort method; and considering the fact that I posted the Bubble Sort method, it only fits that I show you the Selection Sort method as well.
I programmed it in Java since it's the only thing that I could use at the moment to test the code, but the method itself is the same regardless of the language so it shouldn't be a problem to understand how to convert it to GScript for whomever might use it.
SelectionSort.java:
PHP Code:
/*
*@author Gambet
*/
public class SelectionSort
{
double dataSet[] = {1, 6, 4, 2, 5, 8, 20, 100, 54, 1000, 523};
public void selectionSort()
{
for (int a = 0; a < dataSet.length-1; a++)
{
for (int b = a+1; b < dataSet.length; b++)
{
if (dataSet[b] < dataSet[a])
{
double results = dataSet[b];
dataSet[b] = dataSet[a];
dataSet[a] = results;
}
}
}
}
public void showResults()
{
for(int sorted = 0; sorted < dataSet.length; sorted++)
{
System.out.println(dataSet[sorted]);
}
}
}
TestSelectionSort.java:
PHP Code:
class TestSelectionSort
{
public static void main(String[] args)
{
SelectionSort s = new SelectionSort();
s.selectionSort();
s.showResults();
}
}
Quote:
Originally Posted by Results
1.0
2.0
4.0
5.0
6.0
8.0
20.0
54.0
100.0
523.0
1000.0
|
The above code sorts from
least to greatest. To convert from greatest to least, switch:
PHP Code:
if (dataSet[b] < dataSet[a])
to
PHP Code:
if (dataSet[b] > dataSet[a])
NOTE: I used the same set of values that I used for the Bubble Sort algorithm.