Example one:
Public classsort{//Insert Sort/*The basic idea of a direct insert sort (insertion sort) is to insert a record to be sorted each time, by its keyword size, into the appropriate position in the previously ordered subsequence until all records have been inserted. Set the array to a[0...n-1]. 1. Initially, a[0] self into 1 ordered areas, unordered area is a[1..n-1]. Make I=1 2. Incorporating A[i] into the ordered interval of A[0...I] formed in the current ordered region A[0...i-1]. 3. i++ and repeat the second step until the i==n-1. Sorting is complete. */ Public Static int[] Insertsort (int[] intarray) { intSize=intarray.length; for(inti=0;i<size-1;i++){ for(intJ=i; J >=0&&intarray[j+1]<intarray[j];j--) { intTemp=intarray[j+1]; Intarray[j+1]=Intarray[j]; INTARRAY[J]=temp; } } returnIntarray; }//Bubble Sort Public Static int[] Bubblesort (int[] intarray) { intSize=intarray.length; for(inti=0;i<size-1;i++){ for(intj=0; J <size-i-1;j++)//Front is j--, this is J + + { if(Intarray[j]>intarray[j+1]) {//cannot be judged by the condition, but should be circulating here intTemp=intarray[j+1]; Intarray[j+1]=Intarray[j]; INTARRAY[J]=temp; } } } returnIntarray; }//Select sort: For example, in an unordered array of length n, traversing n data on the first pass, finding the smallest of the values to be exchanged with the first element, and the second traversing the remaining N-1 data to find the smallest value exchanged with the second element ... Section N-1 traverses the remaining 2 data to find out the smallest of the values exchanged with the N-1 element, so that the selection is complete. Public Static int[] Selectsort (int[] intarray) { intSize=intarray.length; for(inti=0;i<size-1;i++){ intindex=i; for(intj=i+1; J <size;j++)//find the minimum value, the second small value, and put it in front of each { if(Intarray[i]>intarray[j]) {//I'm here for I and J, not J and J+1. inttemp=Intarray[i]; Intarray[i]=Intarray[j]; INTARRAY[J]=temp; } } } returnIntarray; } Public Static voidMain (string[] args) {int[] arr={2,5,7,1,6,11,3,8}; //Insert Sort//Sort.insertsort (arr);Sort.selectsort (arr); //Bubble Sort//Sort.bubblesort (arr); for(intI:arr) {System.out.println (i); } }}
Various sorting algorithms