几种排序的java实现:选择、插入、冒泡、快排

来源:互联网 发布:神话崔文子 知乎 编辑:程序博客网 时间:2024/06/06 08:34
import java.io.*;
import java.util.*;
/*
 * 5 6 8 7 1 1 2 5 5
 */
public class mySort {
double[] arrayToSort = null;
public mySort(){
ArrayList<String> temp = new ArrayList<String>();
InputStreamReader stdin = new InputStreamReader(System.in); 
BufferedReader br = new BufferedReader(stdin);
String readin = null;
System.out.println("please input the numbers to be sorted \n");
do{
try{
readin = br.readLine();
}catch(Exception e){
e.printStackTrace();
}
String[] tempStr = readin.split(" ");
for(int i = 0; i < tempStr.length; i++){
temp.add(tempStr[i]);
}
}while(!readin.isEmpty());
arrayToSort = new double[temp.size() - 1];
int i = 0;
Iterator<String> it = temp.iterator();
while(it.hasNext() && i != temp.size()-1){
arrayToSort[i++] = Double.parseDouble(it.next());
}
}
public void selectSort(){
double max = 0;
int maxloc = 0;
for(int i = 0; i < arrayToSort.length; i++){
max = arrayToSort[i];
maxloc = i;
for(int j = i + 1; j <arrayToSort.length; j++){
if(arrayToSort[j] >  max){
max = arrayToSort[j];
maxloc = j;
}
}
if(maxloc != i){
double temp = arrayToSort[i];
arrayToSort[i] = arrayToSort[maxloc];
arrayToSort[maxloc] = temp;
}
}

}
public void insertSort(){
for(int i = arrayToSort.length - 1; i > 0; i--){
if(arrayToSort[i] > arrayToSort[i - 1]){
mySort.exchange(arrayToSort, i, i - 1);
}
}
for(int i = 1; i < arrayToSort.length; i++){
double v = arrayToSort[i]; int j = i;
while(arrayToSort[j] > arrayToSort[j - 1]){
mySort.exchange(arrayToSort, j, j - 1);
j--;
}
arrayToSort[j] = v;
}
}
public void bubbleSort(){
for(int i = arrayToSort.length - 1; i > 0; i--){
int key = 0;
for(int j = 1; j <= i; j++){
if(arrayToSort[j] > arrayToSort[j - 1]){
mySort.exchange(arrayToSort, j, j - 1);
key = 1;
}
}
if(key == 0)
break;
}

}
public void qSort(){
qSortFunc(arrayToSort,0,arrayToSort.length - 1);
}
public void qSortFunc(double[] a, int l, int r){
if(l >= r) return;
int p = partition(a,l,r);
qSortFunc(a,l,p - 1);
qSortFunc(a,p + 1,r);
}
public int partition(double[] a, int l, int r){
int i = l + 1; int j = r; double key = a[l];
while(true){
while(a[j] < key)j--;
while(a[i] > key){
i ++;
if(i >= r){
break;
}
}


if(i >= j){
mySort.exchange(a, j, l);
break;
}


mySort.exchange(a, i, j);
i++;
j--;
}
System.out.print("left:  ");
mySort.show(arrayToSort, l, j);
System.out.print("right:  ");
mySort.show(arrayToSort, j, r);
return j;

}
public static void exchange(double[] a, int i ,int j){
double temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void show(double[] a, int i, int j){
for(;i<=j;i++){
System.out.print(a[i] + " ");
}
System.out.println("\n");
}


public static void main(String[] args){
mySort test = new mySort();
test.qSort();
for(double i : test.arrayToSort){
System.out.print(i + " ");
}

}


}
原创粉丝点击