参考《数据结构(C++语言描述)》朱战力编著,练习了冒泡,快速,选择三种排序。
附件有代码和截图,
冒泡排序:
package BubbleSort;
public class BubbleSort {
/**
* 2011-11-18
* edit by QWR
*/
public static void BubbleSort(final int a[]){
int i,j,flag = 1;
int temp;
int n = a.length;
for(i=1;i < n && flag==1;i++){
flag = 0;
for(j = 0;j < n-i ; j++){
if(a[j] > a[j+1]){
flag = 1;
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
int a[] = {98,68,12,100,36,78,7,16,88,69,33,21};
System.out.println("Befor sort:");
for(int i=1;i<a.length;i++ ){
System.out.print(a[i]+" ," );
}
System.out.println();
BubbleSort(a);
System.out.println("After sort:");
for(int i=1;i<a.length;i++ ){
System.out.print(a[i]+" ," );
}
}
}
//---------------------------------------------------
快速排序:
package QuickSort;
public class QuickSort {
/**2011-11-19
* edit by QWR
*/
public static void QuickSort(int[] a, int low, int high) {
int i = low;
int j = high;
int temp = a[low];
while(i < j){
while(i < j && temp <= a[j]){ j--; }
if( i < j){
a[i] = a[j];
i++;
}
while( i <j){ i++; }
if(i < j){
a[j] = a[i];
j--;
}
}
a[i] = temp;
if(low <i){ QuickSort(a, low, i-1); }
if(i<high){ QuickSort(a, j+1, high);}
}
public static void main(String[] args) {
int a[] = {98,68,12,100,36,78,7,16,88,69,33,21};
System.out.println("Befor sort:");
for(int i=1;i<a.length;i++ ){
System.out.print(a[i]+" ," );
}
System.out.println();
QuickSort(a , 0, a.length-1);
System.out.println("After sort:");
for(int i=1;i<a.length;i++ ){
System.out.print(a[i]+" ," );
}
}
}
//-----------------------------------------
选择排序:
package SelectSort;
public class SelectSort {
/**
* 2011-11-19
* edit by QWR
*/
public static void SelectSort(int a[]){
int i , j , small;
int temp ;
int n = a.length;
for( i = 0; i < n-1; i++){
small = i; //设第i个数据元素关键字最小
for( j=i; j < n; j++){ //寻找关键字最小的数据元素
if(a[j] < a[small] ){
small = j; //记住最小的元素下标
}
}
if(small != i){ //当最小元素的下标不为i时交换元素
temp = a[i];
a[i] = a[small];
a[small] = temp;
}
}
}
public static void main(String[] args) {
int a[] = {98,68,12,100,36,78,7,16,88,69,33,21};
System.out.println("Befor sort:");
for(int i=1;i<a.length;i++ ){
System.out.print(a[i]+" ," );
}
System.out.println();
SelectSort(a);
System.out.println("After sort:");
for(int i=1;i<a.length;i++ ){
System.out.print(a[i]+" ," );
}
}
}