View Single Post
  #1  
Old 10-11-2008, 09:00 AM
Gambet Gambet is offline
Registered User
Join Date: Oct 2003
Posts: 2,712
Gambet is on a distinguished road
Sorting Data: Selection Sort

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[] = {16425820100541000523};

  public 
void selectionSort()
  {
   for (
int a 0dataSet.length-1a++)
    {
     for (
int b a+1dataSet.lengthb++)
      { 
       if (
dataSet[b] < dataSet[a])
        {
         
double results dataSet[b];
         
dataSet[b] = dataSet[a];
         
dataSet[a] = results;
        } 
      }
    }    
  }

  public 
void showResults()
  {
   for(
int sorted 0sorted dataSet.lengthsorted++)
    {
     
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.

Last edited by Darlene159; 09-16-2009 at 04:06 AM..
Reply With Quote