快速排序(Java隨機位置快排實現)
阿新 • • 發佈:2019-01-23
package cn.edu.nwsuaf.cie.qhs;
import java.util.Random;
import java.util.Scanner;
//
public class QuickSort {
private int initArray[];
public int[] getInitArray() {
return initArray;
}
public void setInitArray(int[] initArray) {
this.initArray = initArray;
}
public QuickSort() {
// TODO Auto-generated constructor stub
}
public QuickSort(int[] array) {
this.initArray = array;
}
public void random_partion(int start, int length) {//核心程式碼(隨機位置二分排序)
if (length <= 1)
return;
Random rand = new Random();
int index = rand.nextInt(length) + start;
int i = start - 1;
int j = start;
// System.out.println("start--->"+start+"length--->"+length+"i--->"+i+"j--->"+j+"index--->"+index+"start+length-1--->"+(start+length-1));
this.swap(index, start + length - 1);
for (j = start; j < start + length; j++) {
if (initArray[j] < initArray[start + length - 1]) {
this.swap(++i, j);
}
}
this.swap(++i, start + length - 1);
random_partion(start, i - start + 1);
random_partion(i + 1, length + start - i - 1);
}
public int[] quickSorted() {
this.random_partion(0, initArray.length);
return initArray;
}
public void swap(int a, int b) {
int temp = initArray[a];
initArray[a] = initArray[b];
initArray[b] = temp;
}
public static void main(String[] args) {
// int[] array = { 12012, 3, 945, 965, 66, 232, 65, 7, 8, 898, 56, 878,
// 170, 13, 5 };
QuickSort sort = new QuickSort();
int[] array;
int length;
import java.util.Random;
import java.util.Scanner;
//
public class QuickSort {
private int initArray[];
public int[] getInitArray() {
return initArray;
}
public void setInitArray(int[] initArray) {
this.initArray = initArray;
}
public QuickSort() {
// TODO Auto-generated constructor stub
}
public QuickSort(int[] array) {
this.initArray = array;
}
public void random_partion(int start, int length) {//核心程式碼(隨機位置二分排序)
if (length <= 1)
return;
Random rand = new Random();
int index = rand.nextInt(length) + start;
int i = start - 1;
int j = start;
// System.out.println("start--->"+start+"length--->"+length+"i--->"+i+"j--->"+j+"index--->"+index+"start+length-1--->"+(start+length-1));
this.swap(index, start + length - 1);
for (j = start; j < start + length; j++) {
if (initArray[j] < initArray[start + length - 1]) {
this.swap(++i, j);
}
}
this.swap(++i, start + length - 1);
random_partion(start, i - start + 1);
random_partion(i + 1, length + start - i - 1);
}
public int[] quickSorted() {
this.random_partion(0, initArray.length);
return initArray;
}
public void swap(int a, int b) {
int temp = initArray[a];
initArray[a] = initArray[b];
initArray[b] = temp;
}
public static void main(String[] args) {
// int[] array = { 12012, 3, 945, 965, 66, 232, 65, 7, 8, 898, 56, 878,
// 170, 13, 5 };
QuickSort sort = new QuickSort();
int[] array;
int length;