1 Importjava.util.Arrays;2 3 /**4 * Various sorting algorithms are sorted from small to large5 */6 Public classTest {7 8 Public Static voidMain (String args[]) {9 int[] n = {5, 2, 3, 4, 1 };Ten int[] N1, N2, N3; OneN1 = N2 = N3 =arrays.copyof (n, n.length); A -System.out.println ("Original array:"); - PrintArray (n); the - Selectionsort (N1); -System.out.println ("\ n Select sort after:"); - PrintArray (N1); + - Bubblesort (n2); +System.out.println ("\ n bubble sort after:"); A PrintArray (n2); at - Insertionsort (n3); -System.out.println ("\ n Insert sort after:"); - PrintArray (n3); - } - in /**Select sort: The smallest element is first determined*/ - Private Static voidSelectionsort (intnumber[]) { to for(inti = 0; i < number.length-1; i++) { + //sort the current unordered interval score[i......length-1] - for(intj = i + 1; J < Number.length; J + +) { the if(Number[i] >Number[j]) { * inttemp =Number[i]; $Number[i] =Number[j];Panax NotoginsengNUMBER[J] =temp; - } the } + A } the } + - /**Bubble Sort: The first to determine is the largest element*/ $ Private Static voidBubblesort (intnumber[]) { $ for(inti = 0; i < number.length-1; i++) { - //sort the current unordered interval score[0......length-i-1] - for(intj = 0; J < number.length-i-1; J + +) { the if(Number[j] > number[j + 1]) { - inttemp =Number[j];WuyiNUMBER[J] = number[j + 1]; theNumber[j + 1] =temp; - } Wu } - } About } $ - /**Insert Sort: Continuously inserts elements into already sorted data (note the order of insertions)*/ - Private Static voidInsertionsort (int[] list) { - for(inti = 1; i < list.length; i++) { A intCurrentelement =List[i]; + //Insert list[i] between list[0]~list[i-1], so list[0]~list[i] is in order. the intJ; - for(j = i-1; J >= 0 && list[j] > currentelement; j--) { $List[j + 1] =List[j]; the } the //Insert current element into list[j+1] theList[j + 1] =currentelement; the } - } in the /**to print an element in an array*/ the Private Static voidPrintArray (intnumber[]) { About for(intI:number) { theSystem.out.print (i + "\ T")); the } the } +}
Operation Result:
Java implementation of several sort algorithms