1、冒泡排序 时间复杂度O(n^2)
public class Test {
public static void bubblesort(int[] array){
for(int i=0;i<array.length-1;i++){ //冒泡次数
for(int j=0;j<array.length-i-1;j++){ //冒泡步骤
int temp=0;
if(array[j]>array[j+1]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int[] arr=new int[5];
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
Sort(arr);
for(int ans:arr){
System.out.println(ans);
}
}
}
2、快速排序 时间复杂度O(n*logn)
public class Test1 {
public static void quickSort(int[] arr, int startIndex, int endIndex) {
// 递归结束条件:startIndex大等于endIndex的时候
if (startIndex >= endIndex) {
return;
}
// 得到基准元素位置
int pivotIndex = partition(arr, startIndex, endIndex);
// 根据基准元素,分成两部分递归排序
quickSort(arr, startIndex, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, endIndex);
}
/**
* 分治(双边循环法)
* @param arr 待交换的数组
* @param startIndex 起始下标
* @param endIndex 结束下标
*/
private static int partition(int[] arr, int startIndex, int endIndex) {
// 取第一个位置的元素作为基准元素(也可以选择随机位置)
int pivot = arr[startIndex];
int left = startIndex;
int right = endIndex;
while( left != right) {
//控制right指针比较并左移
while(left<right && arr[right] > pivot){
right--;
}
//控制left指针比较并右移
while( left<right && arr[left] <= pivot) {
left++;
}
//交换left和right指向的元素
if(left<right) {
int p = arr[left];
arr[left] = arr[right];
arr[right] = p;
}
}
//pivot和指针重合点交换
arr[startIndex] = arr[left];
arr[left] = pivot;
return left;
}
public static void main(String[] args) {
int[] array=new int[]{4,6,8,3,1,5};
quickSort(array,0,array.length-1);
for(int ans:array){
System.out.println(ans);
}
}
}
3、选择排序
选择排序原理即是,遍历元素找到一个最小(或最大)的元素,把它放在第一个位置,然后再在剩余元素中找到最小(或最大)的元素,把它放在第二个位置,依次下去,完成排序。
通过第一个元素值arr[0]和后面arr[1]比较,小的值放前面0位置、再将arr[0]和arr[2]分别比较,小的值放前面0位置......则一轮循环后,全数组最小的数放在最前面,依次往后遍历循环将第二小值放在arr[1]......
public class Test{
public static void Sort(int[] arr) {
for(int i=0;i<arr.length;i++){
int minindex=i; //用来记录最小值的索引位置,默认值为i
for(int j=i+1;j<arr.length;j++){
if(arr[j]<arr[minindex]){
minindex=j; //遍历 i+1~length 的值,找到其中最小值的位置
}
// 交换当前索引i和最小值索引minIndex两处的值,把最小数放前面
if(minindex!=i){
int temp=arr[minindex];
arr[minindex]=arr[i];
arr[i]=temp;
}
}
}
}
public static void main(String[] args) {
int[] array=new int[]{4,3,1,5,7,6,2};
Sort(array);
for(int num:array){
System.out.println(num+"");
}
}
}
4、归并排序
5、插入排序