ImportJava.util.Scanner; Public classMain {Private Static intCount=0; Public Static voidMergeSort (intA[],intLowintHigh ) { if(low<High ) { intMid= (Low+high) >>1; MergeSort (A,low,mid); MergeSort (A,mid+1, high); Merge (A,low,mid,high); } } Private Static voidMergeint[] A,intLowintMidintHigh ) { inttemp[]=New int[High-low+1]; Open up extra SpaceintIndex=0; intbeg1=Low ; intBeg2=mid+1; while(beg1<=mid&&beg2<=High )//If both are present, select one of the fewer {if(a[beg1]<=A[BEG2]) {Temp[index++]=a[beg1++]; } Else{Temp[index++]=a[beg2++]; Count+=mid-beg1+1; If the latter is selected, there will be an inverse number of mid-beg1+1 for the latter}} while(beg1<=mid)//The remaining element {Temp[index++]=a[beg1++]; } while(beg2<=High ) {Temp[index++]=a[beg2++]; } for(inti=0;i<index;i++) {A[low+i]=Temp[i]; } } Public Static voidMain (string[] args) {//TODO auto-generated Method StubScanner scn=NewScanner (system.in); intlen=Scn.nextint (); while(len-->0) {Count=0; intLen2=Scn.nextint (); inta[]=New int[Len2]; for(inti=0;i<len2;i++) {A[i]=Scn.nextint (); } mergesort (A,0,len2-1); System.out.println (count); } }}
Sort of list in Leetcode
Public classSolution { PublicListNode sortlist (ListNode head) {if(head==NULL)return NULL; if(head.next==NULL)returnHead; ListNode List=Split (head); returnMerge (Sortlist (head), sortlist (list)); } //divide into and part, return the middle address PrivateListNode Split (ListNode head) {ListNode Qucik=Head; ListNode Slow=Head; ListNode Pre=NULL; while(qucik!=NULL) {Pre=slow; Slow=Slow.next; Qucik=Qucik.next; if(qucik!=NULL) qucik=Qucik.next; } Pre.next=NULL; returnslow; } Publiclistnode Merge (ListNode head,listnode middle) {listnode P1=Head; ListNode P2=Middle; ListNode h=NewListNode (-1); ListNode Tail=h;//insert into tail; while(p1!=NULL&&p2!=NULL) { if(p1.val<=p2.val) {Tail.next=P1; Tail=Tail.next; P1=P1.next; } Else{Tail.next=P2; Tail=Tail.next; P2=P2.next; } } if(p1!=NULL) {Tail.next=P1; Tail=Tail.next; } if(p2!=NULL) {Tail.next=P2; Tail=Tail.next; } returnH.next; } }
Multi-threaded Merge sort
Merging sort in order to merge and sort the list of inverse numbers multithreading merge sort Java