主要排序算法实现
程序功能:输入10个整数,输出排序结果(升序)。
//冒泡排序
public class SortTest{
public static void bubbleSort(int[] source){
for(int i=source.length-1;i>0;i--){
for(int j=0;j<i;j++){
if(source[j]>source[j+1]){
swap(source,j,j+1);
}
}
}
}
private static void swap(int [] source, int x, int y){
int temp = source[x];
source[x] = source[y];
source[y] = source[x];
}
public static void main(String[] args){
int [] a= {4,2,1,6,3,6,0,-5,1,1};
int i;
bubbleSort(a);
for(i=0;i<10;i++){
System.out.printf("%d ",a[i]);
}
}
}
//选择排序
public class SortTest{
public static void selectSort(int[] source){
for(int i=0;i<source.length;i++){
for(int j=i+1;j<source.length;j++){
if(source[i]>source[j]){
swap(source,i,j);
}
}
}
}
private static void swap(int [] source, int x, int y){
int temp = source[x];
source[x] = source[y];
source[y] = temp;
}
public static void main(String[] args){
int [] a= {4,2,1,6,3,6,0,-5,1,1};
int i;
bubbleSort(a);
for(i=0;i<10;i++){
System.out.printf("%d ",a[i]);
}
}
}
//插入排序
public class SortTest{
public static void insertSort(int[] source){
for(int i=1;i<source.length;i++){
for(int j=i;(j>0)&&(source[j]<source[j-1]);j--){
swap(source,j,j-1);
}
}
}
private static void swap(int [] source, int x, int y){
int temp = source[x];
source[x] = source[y];
source[y] = source[x];
}
public static void main(String[] args){
int [] a= {4,2,1,6,3,6,0,-5,1,1};
int i;
bubbleSort(a);
for(i=0;i<10;i++){
System.out.printf("%d ",a[i]);
}
}
}
//Shell排序
public class ShellSort{
public static int[] a={4,2,1,6,3,6,0,-5,1,-1};
public static void main(String args[]){
int i;
int Index = a.length;
System.out.print("befor sort: ");
for(i=0;i<Index-1;i++)
System.out.printf("%3s ",a[i]);
System.out.println("");
shellSort(Index-1);
System.out.print("after sort: ");
for(i=0;i<Index-1;i++){
System.out.printf("%3s ",a[i]);
}
System.out.println("");
}
public static void shellSort(int Index){
int i,j,k;
int temp;
boolean change;
int DataLength;
int Pointer;
DataLength = (int)Index/2;
while(DataLength!=0)
{
for(j=DataLength;j<Index;j++){
change=false;
temp=a[j];
Pointer=j-DataLength;
while(temp<a[Pointer] && Pointer>=0 && Pointer<=Index){
a[Pointer+DataLength]=a[Pointer];
Pointer = Pointer-DataLength;
change=true;
if(Pointer<0 || Pointer>Index)
break;
}
a[Pointer+DataLength]=temp;
if(change){
System.out.print("sorting... ");
for(k=0;k<Index;k++)
System.out.printf("%3s ",a[k]);
System.out.println("");
}
}
DataLength = DataLength/2;
}
}
}