排序
参考:https://www.cnblogs.com/herozhi/p/5880939.html
package com.lkr.dataStructure;
import java.util.Arrays;
import static com.sun.tools.javac.jvm.ByteCodes.swap;
public class Sort {
public static void main(String[] args){
int [] unsortedArray = {4,55,5,6,1,98,23,544,2,3,5,78,34};
//System.out.println("排序前数组为:"+ Arrays.toString(unsortedArray));
//int [] bSortArr = Sort.bubbleSort(unsortedArray);
//System.out.println("冒泡排序结果为:" + Arrays.toString(bSortArr));
//int [] sSortArr = Sort.selectSort(unsortedArray);
//System.out.println("选择排序结果为:" + Arrays.toString(sSortArr));
//int [] iSortArr = Sort.insertSort(unsortedArray);
//System.out.println("插入排序结果为:" + Arrays.toString(iSortArr));
Sort.quickSort(unsortedArray,0,unsortedArray.length-1);
System.out.println("快速排序结果为:" + Arrays.toString(unsortedArray));
}
//冒泡排序
public static int[] bubbleSort(int [] array){
int temp;
for (int i=0;i<array.length-1;i++){ //排序趟数
for(int j=0;j<array.length-i-1;j++){ //每一趟排序多少次
if(array[j+1] < array[j]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
return array;
}
//选择排序
public static int[] selectSort(int [] array){
int i,j,k;
for (i=0;i<array.length-1;i++){ //做第i趟排序
k = i;
for (j=i+1;j<array.length;j++){ //找出最小的数
if(array[j] < array[k]){
k = j; //记录下目前最小值所在位置
}
}
//交换i和k
if(i != k){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
return array;
}
//插入排序
public static int[] insertSort(int [] array){
for (int i=1;i<array.length;i++){ //
int temp = array[i];
int left = i-1;
while (left >= 0 && array[left] > temp){
array[left+1] = array[left];
left--;
}
array[left+1] = temp;
}
return array;
}
//快速排序
public static void quickSort(int [] array,int low, int high){
if(low > high){
return ;
}
int i = low;
int j = high;
int key = array[low]; //key为基准位
while (i<j){
//先看右边,依次向左递减
while (i<j && array[j] >= key){
j--;
}
//在看左边,依次向右递增
while (i<j && array[i] <= key){
i++;
}
//如果满足条件则交换
if(i<j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
//将基准位与i,j位置相等的数字交换
array[low] = array[i];
array[i] = key;
//递归调用左半数组
quickSort(array,low,j-1);
//递归调用右半数组
quickSort(array,j+1,high);
return ;
}
}