code about sorting array in java

1.选择排序 代码如下:
public static void main(String[] args) { int [] arr = {1, 36, 45, 21, 3 }; selection(arr); for (int i = 0; i < arr.length; i++) { System.out.print(" arr["+ i + “] " + arr[i] ); } }//主函数 public static void selection(int[] arr) { for (int x = 0; x < arr.length-1; x++) { for (int y = x + 1; y < arr.length; y++) { if(arr[x] > arr[y]) swap(arr, x, y); } } }//选择排序 public static void swap(int [] arr, int x, int y) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; }//排序中的swap函数 2冒牌排序 public static void main(String[] args) { int [] arr = {1, 36, 45, 21, 3 }; bubble(arr); for (int i = 0; i < arr.length; i++) {












System.out.print(" arr["+ i + "] " + arr[i] ); } }//main function
public static void bubble(int[] arr) { for (int x = 0; x < arr .length-1; x++) { for (int y = 0; y < arr.length - 1 - x; y++) { if(arr[y] > arr[y+1]) { int swap = arr[y] ; arr[y] = arr[y + 1]; arr[y + 1] = swap; } } } }//Bubble sort code These are just two ideas and algorithms, in Java, you can use Arrays.sort directly The () function implements sorting and is faster! The code is as follows: public class Arrys { public static void main(String[] args) { · int [] arr = {1, 36, 45, 21, 3 }; Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { System.out.print(” arr["+ i + "] " + arr[i] ); } }








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324156393&siteId=291194637