Wednesday, September 28, 2011

Implement Insertion Sort in Java

Example of Insertion Sort using Java code:
public class InsertionSort {

public static void main(String[] args) {
System.out.println("Hello, Java-Buddy!");

MyData myData = new MyData();
myData.show(); //Before sort
myData.InsertionSort();
myData.show(); //After sort
}


static class MyData {

final static int LENGTH = 10;
static int[] data = new int[LENGTH];

MyData(){
//Generate the random data
for (int i = 0; i < 10; i++) {
data[i] = (int)(100.0*Math.random());
}
}

void InsertionSort(){
int cur, j;

for (int i = 1; i < LENGTH; i++) {
cur = data[i];
j = i - 1;

while ((j >= 0) && (data[j] > cur)) {
data[j + 1] = data[j];
j--;
}

data[j + 1] = cur;
}
}

void show(){
for (int i = 0; i < 10; i++) {
System.out.print(data[i] + " ");
}
System.out.println("\n");
}

}
}



Insertion Sort in Java



No comments:

Post a Comment