Created
October 8, 2012 19:19
-
-
Save shannonbradshaw/3854357 to your computer and use it in GitHub Desktop.
SelectionSort.java for CSCI 230, Drew University
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
import structure5.*; | |
public class SelectionSort | |
{ | |
public static void main(String args[]) | |
{ | |
ReadStream r = new ReadStream(); | |
int n = r.readInt(); | |
int data[] = new int[n]; | |
int i; | |
for (i = 0; i < n; i++) | |
{ | |
data[i] = r.readInt(); | |
} | |
selectionSort(data,n); | |
for (i = 0; i < n; i++) | |
{ | |
System.out.print(data[i]+" "); | |
if (((i+1) % 15) == 0) System.out.println(); | |
} | |
System.out.println(); | |
} | |
public static void selectionSort(int data[], int n) | |
// pre: 0 <= n <= data.length | |
// post: values in data[0..n-1] are in ascending order | |
{ | |
int numUnsorted = n; | |
int index; // general index | |
int max; // index of largest value | |
while (numUnsorted > 0) | |
{ | |
// determine maximum value in array | |
max = 0; | |
for (index = 1; index < numUnsorted; index++) | |
{ | |
if (data[max] < data[index]) max = index; | |
} | |
swap(data,max,numUnsorted-1); | |
numUnsorted--; | |
} | |
} | |
public static void swap(int data[], int i, int j) | |
// pre: 0 <= i,j < data.length | |
// post: data[i] and data[j] are exchanged | |
{ | |
int temp; | |
temp = data[i]; | |
data[i] = data[j]; | |
data[j] = temp; | |
} | |
public static <T> void swap(Vector<T> data, int i, int j) | |
// pre: 0 <= i,j < data.size() | |
// post: i-th j-th elements of data are exchanged | |
{ | |
T temp; | |
temp = data.get(i); | |
data.set(i,data.get(j)); | |
data.set(j,temp); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment