package com.hello; public class HelloJava { /** * 冒泡排序(通过一次一次的循环,根据相近两个值进行比较,将大的值往下移) * @author MR ZHANG * @param arr * @return */ public static void getBubbleSort(int[] arr){ for(int i = 1;i< arr.length-1;i++){ for(int j=0; j< arr.length-i;j++){ if(arr[j]>=arr[j+1]){ int temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; } } } } /** * 选择排序(每次循环选择剩余的数据中最大数的下标,然后保存亲赖,最后在进行替换) * @author Mrzhang * @param arr * @return */ public static void getSelectSort(int[] arr){ for(int i= 1;i<arr.length-1;i++){ int index = 0; for(int j=0;j<=arr.length-i;j++){ if(arr[j]>=arr[index]){ index = j; } } int temp = arr[arr.length-i]; arr[arr.length-i] = arr[index]; arr[index] = temp; } } /** * 快速排序(选择一个值作为KEY,然后将大于KEY的值移动到右边,将小于key的值移动到左边) * @param arr * @param lowIndex * @param highIndex */ public static void getQuickSort(int[] arr,int lowIndex,int highIndex){ int low = lowIndex,high = highIndex; while(low < high){ while(high > low && arr[high] >= arr[low]){ high--; } if(high > low){ int temp = arr[high]; arr[high] = arr[low]; arr[low] = temp; } while(low < high && arr[low] < arr[high]){ low++; } if(low < high){ int temp = arr[low]; arr[low] = arr[high]; arr[high]= temp; } } if(high > lowIndex){ getQuickSort(arr,lowIndex,--high); } if(low < highIndex){ getQuickSort(arr,++low,highIndex); } } public static void main(String[] args){ int[] arr = {1,9,6,2,2,8,5,4,3,7}; System.out.println("原始数组为:"); printArry(arr);//输出数组 getQuickSort(arr,0,arr.length-1);//对数组进行快速排序 System.out.println("快速排序后的数组:"); printArry(arr); } public static void printArry(int[] arr){ for(int i : arr){ System.out.print(" " + i); } System.out.println(); } }
冒泡排序,选择排序,快速排序
时间: 2024-10-06 00:12:11