Thanks in advance.
class
import java.util.Random;
public class qsComparison {
public qsComparison() {
}
public class ExecutionTimer {
private long start;
private long end;
public ExecutionTimer() {
reset();
}
public void start() {
start = System.currentTimeMillis();
}
public void end() {
end = System.currentTimeMillis();
}
public double durationInSeconds() {
return ((end - start) / 1000.0);
}
public void reset() {
start = 0;
end = 0;
}
}
public void insertionSort(int a[], int n) {
int temp;
int i;
int j;
for(j = 1; j < n; j++) {
i = j - 1;
temp = a[j];
while(i >= 0 && temp < a[i]) {
a[i+1] = a[i];
i--;
}
a[i+1] = temp;
}
}
public void quicksort(int a[], int left, int right) {
int mid;
int temp;
int i = left;
int j = right;
mid = a[(left + right) / 2];
do {
while(a[i] < mid)
i++;
while(mid < a[j])
j--;
if (i <= j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
while(i <= j);
if(left < j)
quicksort(a, left, j);
if(i < right)
quicksort(a, i, right);
}
public void quickInsertionSort(int a[], int left, int right) {
if(a.length < 30) {
insertionSort(a, a.length);
return;
}
int mid;
int temp;
int i = left;
int j = right;
mid = a[(left + right) / 2];
do {
while(a[i] < mid)
i++;
while(mid < a[j])
j--;
if (i <= j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
while(i <= j);
if(left < j) {
if(mid < 30) {
insertionSort(a, a.length);
return;
}
else {
quicksort(a, left, j);
}
}
if(i < right) {
if(mid < 30) {
insertionSort(a, a.length);
return;
}
else {
quicksort(a, i, right);
}
}
}
public int[] randomList() {
Random r = new Random();
int a[] = new int[1000000];
for(int i = 1; i <= 1000000; i++) {
int j = r.nextInt(101);
a[i - 1] = j;
}
return a;
}
public static void main(String[] args) {
for (int trial = 1; trial <= 3; trial++) {
ExecutionTimer t = new ExecutionTimer();
t.start();
System.out.println("Trial " + trial);
randomList();
quicksort();
t.end();
System.out.println("\n" + t.durationInSeconds() + " seconds\n");
t.start();
quickInsertionSort();
t.end();
System.out.println("\n" + t.durationInSeconds() + " seconds\n");
}
}
}
This post has been edited by mattlyons: 19 April 2010 - 11:20 AM

New Topic/Question
Reply




MultiQuote







|