六种基本排序方式

来源:互联网 发布:爱乐软件 编辑:程序博客网 时间:2024/06/12 23:30
package new03;


public class Demo4 {


/**
* @六种基本排序方式
*/
public static void main(String[] args) {
int[] nums = {38,65,97,76,13,27,49};

sop("原序列的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");

// selectSort(nums);
// insertSort(nums);
// bubbleSort(nums);
// quickSort(nums);
// shellSort(nums);
heapSort(nums);


}

public static void sop(Object o){
System.out.print(o);
}

/**
* 1.选择排序
*/
public static void selectSort(int[] nums){

int index = 0;
for(int i=0;i<nums.length;i++){
int temp = nums[i];
for(int j=i+1;j<nums.length;j++){
if(temp>nums[j]){
temp = nums[j];
index = j;
}
}
nums[index] = nums[i];
nums[i] = temp;
}

sop("选择排序的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");
}

/**
* 2.堆排序
*/
public static void heapSort(int[] nums){


int i;
int len = nums.length;
for(i = len/2-1;i>=0;i--){
minHeapSort(nums,i,len-1);
}
for(i=len-1;i>=0;i--){
int temp = nums[0];
nums[0] = nums[i];
nums[i] = temp;
minHeapSort(nums,0,i-1);
}

sop("堆排序的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");
}


private static void minHeapSort(int[] nums, int pos, int len) {
int temp;
int child;
for(temp = nums[pos];2*pos+1<=len;pos=child){
child = 2*pos+1;
if(child<len && nums[child]>nums[child+1])
child++;
if(nums[child]<temp)
nums[pos] = nums[child];
else
break;
}
nums[pos] = temp;
}


/**
* 3.插入排序
*/
public static void insertSort(int[] nums){
for(int i=1;i<nums.length;i++){
int temp = nums[i];
int j=i;
while(j>0 && temp<nums[j-1]){
nums[j] = nums[--j];
}
nums[j] = temp;
}

sop("插入排序的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");
}

/**
* 4.希尔排序
*/
public static void shellSort(int[] nums){


int len = nums.length;
for(int h = len/2;h>0;h=h/2){
for(int i=h;i<len;i++){
int temp = nums[i];
int j;
for(j =i-h;j>=0;j=j-h){
if(temp<nums[j])
nums[j+h] = nums[j];
else
break;
}
nums[j+h] = temp;
}
}

sop("希尔排序的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");
}

/**
* 5.冒泡排序
*/
public static void bubbleSort(int[] nums){


for(int i=0;i<nums.length-1;i++){
for(int j=0;j<nums.length-i-1;j++){
if(nums[j]>nums[j+1]){
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}


sop("冒泡排序的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");
}



/**
* 6.快速排序
*/
public static void quickSort(int[] nums){

sort1(nums,0,nums.length-1);

sop("快速排序的结果是:");
for(int x:nums){
sop(x+" ");
}
sop("\n");
}
private static void sort1(int[] nums, int low, int high) {
int i = low;
int j = high;

if(i>j)
return;
int temp = nums[i];

while(i<j){
while(i<j && temp<nums[j])
j--;
nums[i++] = nums[j];

while(i<j && temp>nums[i])
i++;
nums[j--] = nums[i];

}
nums[i] = temp;
sort1(nums,low,i-1);
sort1(nums,i+1,high);

}


}
0 0
原创粉丝点击