Java基础03_数组排序

数组排序

  1. 选择排序:每轮选最小的放前面
    1. 将数组中每个元素与第一个元素比较,如果这个元素小于第一个元素,则交换
    2. 循环第一条规则,找到最小的元素,放在第一位
    3. 经过n-1轮比较完成排序
public class SelectionSort {
 public static void main(String[] args) {
 int[] array = {8,2,3,7,1};
 array = selectionSort(array);//调用选择排序的方法
 for (int i = 0; i < array.length; i++) {
 System.out.print(array[i]+",");
 }
 }
public static int[] selectionSort(int[] array) {
 for (int i = 0; i < array.length-1; i++) {
 for (int j = i + 1; j < array.length; j++) {
 if(array[i]>array[j]){ //如果要降序,把大于号改成小于号
 int temp = array[i];
 array[i] = array[j];
 array[j] = temp;
 }
 }
 }
 return array;
 }
}
  1. 冒泡排序:比较相邻元素,大的向后交换,将小的放到前面
public class BubbleSort {
 public static void main(String[] args) {
 int[] array = {8,2,3,7,1};
 array = bubbleSort(array); //调用冒泡排序后得到升序排序后的新数组
 for (int i = 0; i < array.length; i++) {
 if(i == array.length-1){
 System.out.print(array[i]+" "); //最后一个元素后面加空格
 }else {
 System.out.print(array[i]+",");//只要不是最后一个元素就用逗号隔开
 }
 }
 }
 public static int[] bubbleSort(int[] array) {
 for (int i = 0; i < array.length; i++) {
 for (int j = 0; j < array.length-i-1; j++) {
 if(array[j] > array[j+1]) {
 int temp = array[j];
 array[j] = array[j+1];
 array[j+1] = temp;
 }
 }
 }
 return array;
 }
}
  1. 插入排序:
    1. 将数组分为两部分,将后部分的第一个元素逐一与前部分每一个元素比较,如果当前元素校,就移动比较元素
    2. 找到合理位置插入
public class InsertSort {
 public static void main(String[] args) {
 int[] array = {8,2,3,7,1};
 array = insertSort(array);
 System.out.println(Arrays.toString(array));
 }
  public static int[] insertSort(int[] array) {
 int j,temp;
 for (int i = 1; i < array.length; i++) {
 temp = array[i];
 //利用循环找到插入位置:到头j=-1
 for (j = i - 1; j >= 0 && array[j] > temp; j--) {
 array[j+1] = array[j];//[j]->[j+1]向后移动
 }
 array[j + 1] = temp;//将temp的值给array[j+1] ,j+1是因为循环结束后j的值变成-1了
 }
 return array;
 }
}
  1. API快速排序Arrays.sort
    • Arrays.toString(数组名)以数组的形式输出数组元素
    • Arrays.copyOf(array,array.lenth)拷贝(复制)数组
public class ArraysDemo {
 public static void main(String[] args) {
 int[] array = {8,2,3,7,1};
 Arrays.sort(array);//快速排序
 System.out.println(Arrays.toString(array));//以数组的形式输出
 }
}
  1. 排序效率:Arrays.sort(array)>插入排序>选择排序>冒泡排序
posted @ 2021-05-13 09:35  正成为资深程序员的LW  阅读(104)  评论(0编辑  收藏  举报