Created
November 20, 2011 18:18
-
-
Save fb55/1380626 to your computer and use it in GitHub Desktop.
Some sort algorithms (java)
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 java.util.Random; | |
class sort{ | |
public static void main(String[] a){ | |
Sorter[] list = {new InsertionSort(), new BubbleSort(), new QuickSort()}; | |
for(int i = 0; i < list.length; i++){ | |
sort.perform(list[i]); | |
} | |
} | |
private static Random generator = new Random(); | |
private static void perform(Sorter s){ | |
int[] list = new int[1000]; | |
for(int i = 0; i < list.length; i++){ | |
list[i] = sort.generator.nextInt(); | |
} | |
list = s.sort(list); | |
boolean valid = true; | |
for(int i = 1; i < list.length; i++){ | |
if(list[i-1] > list[i]){ | |
valid = false; | |
break; | |
} | |
} | |
System.out.println(s + " sort " + (valid ? "succeeded" : "failed") +"!"); | |
} | |
} | |
abstract class Sorter{ | |
public abstract int[] sort(int[] list); | |
} | |
class InsertionSort extends Sorter{ | |
public int[] sort(int[] list){ | |
int cur, j; | |
for(int i = 1; i < list.length; i++){ | |
cur = list[i]; | |
for(j = i; j > 0 && list[j-1] > cur; j--){ | |
list[j] = list[j-1]; | |
} | |
list[j] = cur; | |
} | |
return list; | |
} | |
public String toString(){ return "Insertion"; }; | |
} | |
class BubbleSort extends Sorter{ | |
public int[] sort(int[] list){ | |
for(int i = 0; i < list.length; i++){ | |
for(int j = i+1; j < list.length; j++){ | |
if(list[i] > list[j]){ | |
int tmp = list[i]; | |
list[i] = list[j]; | |
list[j] = tmp; | |
} | |
} | |
} | |
return list; | |
} | |
public String toString(){ return "Bubble"; }; | |
} | |
class QuickSort extends Sorter{ | |
public int[] sort(int[] list){ | |
return this.sort(list, list.length); | |
} | |
public int[] sort(int[] list, int l){ | |
if(l == 0) return new int[0]; | |
if(l == 1) return list; | |
int pivot = list[--l]; | |
int[] left = new int[l]; | |
int[] right = new int[l]; | |
int leftLength, rightLength = leftLength = 0; | |
for(int i = 0; i < l; i++){ | |
if(list[i] < pivot) left[leftLength++] = list[i]; | |
else right[rightLength++] = list[i]; | |
} | |
left = this.sort(left, leftLength); | |
right = this.sort(right, rightLength); | |
for(int i = 0; i < leftLength; i++) list[i] = left[i]; | |
list[leftLength] = pivot; | |
for(int i = 0; i < rightLength; i++) list[i + leftLength + 1] = right[i]; | |
return list; | |
} | |
public String toString(){ return "Quick"; }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment