Title:
*
Description:
Copyright: Copyright (c) 2005
Company:
public class Sort
{
public Sort()
{
}
int[] s = {12,4,56,44,3,34,32,2,5,21};
int a = 10;
//1、插入排序(先排头两个元素的序,再排头三个元素的序......)
public void insort()
{
int in,out;
for (out = 1;out< a;out++)
{
int temp = s[out];
in = out;
while(in>0&&s[in-1]>=temp)
{
s[in]=s[in-1];
--in;
}
s[in]=temp;
}
for (int j =0;j< a;j++)
{
System.out.println(j+"="+s[j]);
}
}
//2、选择排序(第一轮,每个数与第一个数比较,最小者成为第一个数,...)
public void selectSort()
{
int out,in,min;
for (out =0;out< a-1;out++)
{
min=out;
for (in = out+1;in< a;in++)
{
if (s[in]< s[min])
swap(in,min);
}
}
for (int j =0;j< a;j++)
{
System.out.println(j+"="+s[j]);
}
}
//3、冒泡排序
public void bubbleSort()
{
int out,in;
for(out = a-1;out>1;out--)
{
for (in=0;in< out;in++)
{
if (s[in]>s[in+1])
{
swap(in,in+1);
}
}
}
for (int j =0;j< a;j++)
{
System.out.println(j+"="+s[j]);
}
}
private void swap(int one ,int two)
{
int temp = s[one];
s[one] = s[two];
s[two] = temp;
}
public static void main(String[] args)
{
Sort in = new Sort();
//in.insort();
in.selectSort();
// in.bubbleSort();
}
}
4、快速排序
先取数组的中间元素,并将数组分为两个较小的数组,其中一个数组只含大于
这个中间值的元素,而另一个数组只含小于这个中间值的元素,重复这一过程。
public class arrayQsort{
static void qsort(int array[],int first,int last){
int low=first;
int high=last;
if(first>=last) return;
int mid=array[(first+last)/2];
do{
while(array[low]< mid)
low++;
while(array[high]>mid)
high--;
if(low<=high){
int temp=array[low];
array[low++]=array[high];
array[high--]=temp;
}
}while(low<=high);
qsort(array,first,high);
qsort(array,low,last);
}
public static void main(String[] args){
int[] s = {12,4,56,44,3,34,32,2,5,21};
qsort(s,0,9);
for (int j =0;j<10;j++)
{
System.out.println(j+"="+s[j]);
}
}
}
程序运行的一个结果:
C:\java>java Sort
0=2
1=3
2=4
3=5
4=12
5=21
6=32
7=34
8=44
9=56
C:\java>java arrayQsort
0=2
1=3
2=4
3=5
4=12
5=21
6=32
7=34
8=44
9=56
C:\java>
</td> <td width="193" valign="top" class="ArticleTeitle">