[Hackerrank] insertion sort advanced analysis)

Source: Internet
Author: User

Insertion sort is a simple sorting technique which was covered in previous challenges. sometimes, arrays may be too large for us to wait around for insertion sort to finish. is there some other way we can calculate the number of times insertion sort shifts each elements when sorting an array?

IfKiIs the number of elements over whichIthElement of the array has to shift then total number of shift will beK1 + k2 +... + kN.

Input: 
The first line contains the number of test cases T. t test cases follow. the first line for each case contains N, the number of elements to be sorted. the next line contains N integers A [1], a [2]..., A [n].

Output: 
Output t lines, containing the required answer for each test case.

Constraints: 
1 <= T <= 5
1 <= n <= 100000
1 & lt; = A [I] & lt; = 1000000

 

This is a disgusting question. It's only been done in the morning. The whole person is groose and has not recovered t_t from over 20 hours of driving yesterday.

OK. This is the number of times that the element in the group is moved when insertion sort is used. Of course, the most naive method is to directly perform one-side insertion sort and output the number of moves. This complexity is O (n2) and will time out.

In fact, the number of Moving Elements in insertion sort is equal to the number of backward orders in this sequence. Because, when inserting element a [I] into the array, all the elements in the sorted array that are larger than it will be removed.

So our problem is simply how to quickly find the number of reverse orders of a sequence. There are many methods on the Internet: Binary Search Tree (when the tree is a single binary tree, the algorithm complexity degrades to O (n2), the red and black trees, and the Merge Sorting.

Here we use the Merge Sorting Method: In the Merge Sorting step, there are two arrays AR1 and AR2, which are the first half and the second half of the original array. Insert the smallest element in the header of the AR1 and AR2 arrays to the sorted array. When this smallest element is extracted from AR2, in AR1, the elements after the current cursor are larger than the smallest element, and are located in front of this element in the original array, so at this time, a total of output m-point1 to the number of Reverse Order (M is the length of AR1, point1 is the cursor of the current ar1 ). In this way, we can calculate the inverse order number in the process of merging and sorting.

For example:

As shown in, the picture on the left shows the process of counting the number of reverse orders in the entire merge process. The orange number indicates the reverse order number pair output in each merge. Finally, you can add all the reverse order number pairs.

The diagram on the right shows the process of merging () and (). When merging 2 In the second step, we find that there is a 7-to-2 largest in the first array, in this case, () is the reverse Number of the sequence.

The last detail is that when the header elements of AR1 and AR2 are equal, you can directly take the header elements of AR1 and put them in the merged array.

The Code is as follows:

 1 import java.util.*; 2  3 public class Solution { 4     private static long answer = 0; 5      6     private static int[] Merge(int[] ar1,int[] ar2){ 7         int m = ar1.length; 8         int n = ar2.length; 9         10         int point1 = 0;11         int point2 = 0;12         int index_result = 0;13         int[] result = new int[m+n];14         while(point1 < m && point2 < n){15             if(ar1[point1] < ar2[point2]){16                 result[index_result] = ar1[point1];17                 point1++;18                 index_result++;19             }20             else if(ar1[point1] > ar2[point2]){21                 answer += m - point1;22                 result[index_result] = ar2[point2];23                 index_result++;24                 point2++;25             }26             else{27                 result[index_result] = ar1[point1];28                 index_result++;29                 point1++;30             }31         }32         while(point1 < m){33             result[index_result] = ar1[point1];34             index_result++;35             point1++;36         }37         while(point2 < n){38             answer += m - point1;39             result[index_result] = ar2[point2];40             index_result++;41             point2++;42         }43         return result;44     }45     private static int[] mergeSort(int[] ar){46         int n = ar.length;47         if(n <= 1)48             return ar;49         int mid = n/2;50         int[] ar1 = new int[mid];51         int[] ar2 = new int[n-mid];52         System.arraycopy(ar, 0, ar1, 0, mid);53         System.arraycopy(ar, mid, ar2, 0, n-mid);54         int[] sorted_ar1 = mergeSort(ar1);55         int[] sorted_ar2 = mergeSort(ar2);56         int[] result = Merge(sorted_ar1, sorted_ar2);57         return result;58     }59     public static void main(String[] args) {60         61         Scanner in = new Scanner(System.in);62         int T = in.nextInt();63         for(int k = 0;k < T;k++){64             answer = 0;65             int n = in.nextInt();66             int[] ar = new int[n];67             for(int i = 0;i < n;i++)68                 ar[i] = in.nextInt(); 69             mergeSort(ar);70             System.out.println(answer);71         }72     }73 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.