Sorting needs to be mastered by having a bubbling sort, inserting sort and selecting sort.
Bubble sort: The outer loop goes from back to front, the memory loops from the back to the outer loop, the adjacent array item 22 compares, and the larger value is moved back.
Insert sort: Starts at the middle of the sort process (the program starts with the second array item a[1]), at which point the queue is already part of the picture. At this point, the array items that are behind are inserted one at a time in the ordered partial queue.
Select sort: Starting with the first array item, finding the smallest item in any of the subsequent array items, including the array entry, is swapped with the current item, which in turn bubbles up the minimum value in order.
Example code:
Packagechap03. Bubblesort;//Bubblesort.java//demonstrates bubble sort//To run this Program:c>java bubblesortappclassArraybub {Private Long[] A; Private intNelems; PublicArraybub (intmax) {a=New Long[Max]; Nelems= 0; } Public voidInsertLongvalue) {A[nelems]=value; Nelems++; } Public voiddisplay () { for(intj = 0; J < Nelems; J + +) {System.out.print (A[j]+ " "); } System.out.println (""); } //Bubble Sort Public voidBubblesort () {intOut , in; for(out = nElems-1, out > 1; out--) { for(in = 0; in < out; in++) { if(A[in] > a[in + 1]) {swap (in,+ 1); } } } } //Insert Sort Public voidInsertionsort () {intin, out; //Out are dividing line for(out = 1; out < Nelems; out++) { //Remove marked item Longtemp =A[out]; //start shifts at outin =Out ; while(In > 0 && a[in-1] >=temp) {A[in]= A[in-1]; --In ; } A[in]=temp; } } //Select Sort Public voidSelectionsort () {intOut , in, Min; for(out = 0; out < nElems-1; out++) {min=Out ; for(in = out + 1; < Nelems; in++) { if(A[in] <A[min]) {min=In ; }} swap (out, min); } } Private voidSwapintOneintBoth ) { Longtemp =A[one]; A[one]=A[two]; A[two]=temp; }}classBubblesortapp { Public Static voidMain (string[] args) {intmaxSize = 100; Arraybub arr; Arr=NewArraybub (maxSize); Arr.insert (77); Arr.insert (99); Arr.insert (44); Arr.insert (55); Arr.insert (22); Arr.insert (88); Arr.insert (11); Arr.insert (00); Arr.insert (66); Arr.insert (33); Arr.display (); Arr.bubblesort (); Arr.display (); }}
Java Data Structures and algorithms (2)-Sort (bubble, insert, and select Sort)