| 51 |
irasnyd |
1 |
// Written by Ira Snyder
|
|
|
2 |
|
|
|
3 |
import java.io.*;
|
|
|
4 |
|
|
|
5 |
class SortMethods {
|
| 52 |
irasnyd |
6 |
|
|
|
7 |
// method to sort the array a (passed as a parameter)
|
|
|
8 |
// this will sort in O(n^2) time
|
| 51 |
irasnyd |
9 |
public static Object[] BubbleSort( Object[] a ) {
|
| 52 |
irasnyd |
10 |
//loop from the back of the array moving towards the beginning
|
| 51 |
irasnyd |
11 |
for( int i=a.length-1; i>0; i-- )
|
| 52 |
irasnyd |
12 |
//loop from the beginning of the array to position "i"
|
| 51 |
irasnyd |
13 |
for( int j=0; j<i; j++ )
|
| 52 |
irasnyd |
14 |
//compare elements next to each other, and swap if necessary
|
|
|
15 |
if( a[j] > a[j+1] ) arraySwap(a,j,j+1);
|
| 51 |
irasnyd |
16 |
}
|
|
|
17 |
|
| 52 |
irasnyd |
18 |
public static Object[] ImprovedBubbleSort( Object[] a ) {
|
|
|
19 |
boolean inorder=true;
|
|
|
20 |
|
|
|
21 |
for( int i=a.length-1; i>0; i-- ) {
|
|
|
22 |
inorder=true;
|
|
|
23 |
|
|
|
24 |
for( int j=0; j<i; j++ )
|
|
|
25 |
if( a[j] > a[j+1] ) {
|
|
|
26 |
arraySwap(a,j,j+1);
|
|
|
27 |
inorder=false;
|
|
|
28 |
}
|
|
|
29 |
if(inorder) break; //array sorted, so bail out
|
|
|
30 |
}
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
// method to sort the array a (passed as a paramter)
|
|
|
34 |
// this will sort in O(n^2) time
|
|
|
35 |
public static Object[] SelectionSort( Object[] a ) {
|
|
|
36 |
//loop from the back of the array moving towards the front
|
|
|
37 |
for( int i=a.length-1; i>0; i-- ) {
|
|
|
38 |
//placeholder for the maximum element
|
|
|
39 |
int m=0;
|
|
|
40 |
//find the maximum element in the array
|
|
|
41 |
for( int j=1; j<=i; j++ )
|
|
|
42 |
if( a[j] > a[m] ) m = j;
|
|
|
43 |
|
|
|
44 |
//swap the "i"th element with the maximum element
|
|
|
45 |
arraySwap(a,i,m);
|
|
|
46 |
}
|
|
|
47 |
}
|
|
|
48 |
|
|
|
49 |
// method to sort the array a (passed as a parameter)
|
|
|
50 |
// this will sort in O(n^2) time
|
|
|
51 |
public static Object[] InsertionSort( Object[] a ) {
|
|
|
52 |
//iterate through the array from the beginning to the end
|
|
|
53 |
for ( int i=1; i<a.length; i++ ) {
|
|
|
54 |
//store a[i] in a temp location
|
|
|
55 |
Object ai = a[i];
|
|
|
56 |
int j=i; //start for the inner loop
|
|
|
57 |
|
|
|
58 |
//find the place to insert ai, and shift elements down
|
|
|
59 |
for ( j=i; j>0 && a[j-1]>ai; j-- )
|
|
|
60 |
a[j] = a[j-1]; //shift down
|
|
|
61 |
|
|
|
62 |
//insert ai into position a[j]
|
|
|
63 |
a[j] = ai;
|
|
|
64 |
}
|
|
|
65 |
}
|
|
|
66 |
|
| 51 |
irasnyd |
67 |
//ShellSort
|
|
|
68 |
//MergeSort
|
|
|
69 |
//HeapSort
|
|
|
70 |
//QuickSort
|
|
|
71 |
|
|
|
72 |
public static void arraySwap( Object[] a, int posA, int posB ) {
|
|
|
73 |
Object temp = a[posB]; // temp = B
|
|
|
74 |
a[posB] = a[posA]; // B = A
|
|
|
75 |
a[posA] = temp; // A = temp
|
|
|
76 |
}
|
|
|
77 |
}
|
|
|
78 |
|