Sorting

import java.awt.*;
import java.applet.Applet;

public class SortExamp extends Applet
{
int n[] = { 43, 74, 92, 56, 57, 94, 87, 21, 76, 57, 39, 57, 68 };

public void paint (Graphics g)
{

for (int x = 0; x < n.length; x++) g.drawString(Integer.toString(n[x]),10,10+x*15);
g.drawString (Integer.toString(n[findHiPosition(0)]),50,50);

}

int findHiPosition(int sortStart)
{
int hiPos = 0; int hi = 0;
for (int x = sortStart; x < n.length; x++)
{
if ( n[x] > hi )
{
hi = n[x];
hiPos = x;
}
}
return hiPos;
}

}

HERE IS THE CODE ABOVE RUNNING AS AN APPLET:




 




 





 

HERE IS THE NEXT STEP TOWARDS A SELECTION SORT:


import java.awt.*;
import java.applet.Applet;

public class SortExamp2 extends Applet
{
int n[] = { 43, 74, 92, 56, 57, 94, 87, 21, 76, 57, 39, 57, 68 };
int colSpace = 10;
Button sort = new Button("Sort");

public void paint (Graphics g)
{
for (int x = 0; x < n.length; x++) g.drawString(Integer.toString(n[x]),colSpace,10+x*15);
}

public void init() {add(sort);}

int findHiPosition(int sortStart)
{
int hiPos = 0; int hi = 0;
for (int x = sortStart; x < n.length; x++)
{
if ( n[x] > hi )
{
hi = n[x];
hiPos = x;
}
}
return hiPos;
}

void sort1()
{
int swapPos = findHiPosition(0);
swap(0,swapPos);
}

void swap (int first, int second)
{
int temp = n[first];
n[first] = n[second];
n[second] = temp;
}

public boolean action (Event e,Object o)
{
sort1();
colSpace = 150;
repaint();
return true;
}
}

HERE IS THE APPLET ABOVE RUNNING:

 

 

 

 

 

 

 

NOW, TRY TO FINISH THE SORT. YOU WILL NEED TO ENTER ONLY A FEW LINES OF CODE.  WHEN YOUR PROGRAM RUNS, YOU WILL GET THE LIST SORTED COMPLETELY WHEN THE SORT BUTTON IS PRESSED.  MAKE SURE YOU UNDERSTAND THE CODE ABOVE PERFECTLY FIRST BEFORE YOU TRY TO MAKE CHANGES!!

 

 

 

BuiltWithNOF

[Java at Evergreen] [Syllabus] [To Do List] [Lessons/Programs] [Evaluation/Review] [Help] [FAQ/GWIFO] [Discuss/Reports] [Resources] [Readings] [Portfolio] [Instructor]