Java implementation of several sort algorithms and the sort algorithm java
1 import java. util. arrays; 2 3/** 4 * sorting algorithms from small to large 5 */6 public class Test {7 8 public static void main (String args []) {9 int [] n = {5, 2, 3, 4, 1}; 10 int [] n1, n2, n3; 11 n1 = n2 = n3 = Arrays. copyOf (n, n. length); 12 13 System. out. println ("original array:"); 14 printArray (n); 15 16 selectionSort (n1); 17 System. out. println ("\ n after sorting:"); 18 printArray (n1); 19 20 bubbleSort (n2); 21 System. out. after println ("\ n Bubble Sorting: "); 22 printArray (n2); 23 24 insertionSort (n3); 25 System. out. println ("\ n insert sorting:"); 26 printArray (n3); 27} 28 29/** select sorting: first, the minimum element */30 private static void selectionSort (int number []) {31 for (int I = 0; I <number. length-1; I ++) {32 // score of the unordered range [I ...... length-1] for sorting 33 for (int j = I + 1; j <number. length; j ++) {34 if (number [I]> number [j]) {35 int temp = number [I]; 36 number [I] = number [j]; 37 n Umber [j] = temp; 38} 39} 40 41} 42} 43 44/** Bubble Sorting: the largest element */45 private static void bubbleSort (int number []) is determined first {46 for (int I = 0; I <number. length-1; I ++) {47 // score the current unordered range [0 ...... length-i-1] for sorting 48 for (int j = 0; j <number. length-I-1; j ++) {49 if (number [j]> number [j + 1]) {50 int temp = number [j]; 51 number [j] = number [j + 1]; 52 number [j + 1] = temp; 53} 54} 55} 56} 57 58/** insert sorting: constantly Insert the element to the sorted data (note the insertion sequence) */59 private static void insertionSort (int [] list) {60 for (int I = 1; I <list. length; I ++) {61 int currentElement = list [I]; 62 // Insert list [I] to list [0] ~ Between lists [I-1], so list [0] ~ List [I] is sorted 63 int j; 64 for (j = I-1; j> = 0 & list [j]> currentElement; j --) {65 list [j + 1] = list [j]; 66} 67 // Insert the current element to list [j + 1] 68 list [j + 1] = currentElement; 69} 70} 71 72/** print the elements in the array */73 private static void printArray (int number []) {74 for (int I: number) {75 System. out. print (I + "\ t"); 76} 77} 78}
Running result: