Programming algorithms-Reverse-order code in arrays (C)

Source: Internet
Author: User

Reverse-order code in the array (C)


This address: Http://blog.csdn.net/caroline_wendy


Title: The two numbers in the array assume that the previous number is greater than the following number, then these two numbers form an inverse pair.

Enter an array to find the total number of reverse pairs in this array.


Using the merge sort method, the auxiliary space is a sort of array, in order to compare the larger number in the front, to calculate the overall inverse logarithm, not one by one comparison.


Complexity of Time: O (NLOGN)


Code:

/* * main.cpp * * Created on:2014.6.12 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <stdio.h> #include <stdlib.h> #include <string.h>int inversepairscore (int* data, int* copy, int start, int end) {if (start = = End ) {Copy[start] = Data[start];return 0;}  int length = (end-start)/2;int left = Inversepairscore (copy, data, start, start+length); int right = Inversepairscore (copy, Data, start+length+1, end); int i = start+length; The last digit of the first half is subscript int j = End;int Indexcopy = end;int count = 0;while (I>=start && j>=start+length+1) {if (data[ I] > Data[j]) {copy[indexcopy--] = Data[i--];count + + j-start-length;} else {copy[indexcopy--] = data[j--];}} for (; i>=start;-I.) copy[indexcopy--] = Data[i];for (; j>=start+length+1;--j) copy[indexcopy--] = Data[j];return L Eft+right+count;} int Inversepairs (int* data, int length) {if (data = = NULL | | length < 0) return 0;int *copy = new Int[length];for (int i=0; i<length; ++i) Copy[i] = data[i];int count = Inversepairscore (data, copy, 0, length-1);d elete[] Copy;return count;}    int main (void) {int data[] = {7, 5, 6, 4};int result = Inversepairs (data, 4);    printf ("result =%d\n", result); return 0;}

Output:

result = 5





Programming algorithms-Reverse-order code in arrays (C)

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.