冒泡排序:
/**
* 32,45,34,21,13,33,15,17,71,90
* 13,45,34,32,21,33,15,17,71,90 ----------------1次
* 13,15,45,34,32,33,21,17,71,90 ----------------2次
* ……
* @param args
*/
public static void main(String[] args){
int a={32,45,34,21,13,33,15,17,71,90};
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length-i-1;i++){
if(a[j]>a[j+1]){
int temp=a[j];
int[j]=a[j+1];
int[j+1]=temp;
}
}
}
for(int m=0;m<a.length;m++){
System.out.print(" "+a[m]);
}
}
输出: 13 15 17 21 32 33 34 45 71 90
快速排序:
package com.sort;
public class Qsort {
public static void main(String[] args){
int [] a={32,45,34,21,13,33,15,17,71,90};
QuickSort qSort = new QuickSort();
qSort.data = a;
qSort.sort(0, qSort.data.length-1);
qSort.display();
}
}
class QuickSort{
public int data[];
private int partition(int sortArray[],int low,int hight){
int key= sortArray[low];
while(low<hight){
while(low<hight&&sortArray[hight]>=key)
hight--;
sortArray[low]=sortArray[hight];
while(low<hight && sortArray[low]<=key)
low++;
sortArray[hight] = sortArray[low];
}
sortArray[low] = key;
return low;
}
public void sort(int low,int hight){
if(low<hight){
int result = partition(data,low,hight);
sort(low,result-1);
sort(result+1,hight);
}
}
public void display(){
for(int i=0;i<data.length;i++){
System.out.print(" "+data[i]);
}
}
} 输出: 13 15 17 21 32 33 34 45 71 90