Week1 topics:
- INTRODUCTION
- ASYMPTOTIC ANALYSIS
- DIVIDE & CONQUER ALGORITHMS
Programming assignment: The file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated. Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array.
Question 1 Download the text file here. (Right click and save link as)
This file contains all of the 100,000 integers between 1 and 100,000 (inclusive) in some order, with no integer repeated.
Your task is to compute the number of inversions in the file given, where the ith row of the file indicates the ith entry of an array. Because of the large size of this array, you should implement the fast divide-and-conquer algorithm covered in the video lectures. The numeric answer for the given input file should be typed in the space below. So if your answer is 1198233847, then just type 1198233847 in the space provided without any space / commas / any other punctuation marks. You can make up to 5 attempts, and we'll use the best one for grading. (We do not require you to submit your code, so feel free to use any programming language you want --- just type the final numeric answer in the following space.)
#! /usr/bin/python # coding: UTF-8 import sys def main(): a = [] tweet_file = open("algo.txt") for line in tweet_file: a.append(int(line)) print count_inversions(a, 0, len(a) - 1) def count_inversions(a, p, r): inversions = 0 if p < r: q = (p + r) / 2 inversions += count_inversions(a, p, q) inversions += count_inversions(a, q+1, r) inversions += merge_inversions(a, p, q, r) return inversions INFINITY = 999999 def merge_inversions(a, p, q, r): n1 = q - p + 1 n2 = r - q L = [] R = [] for i in range(n1): L.append(a[p+i]) for j in range(n2): R.append(a[q+j+1]) L.append(INFINITY) R.append(INFINITY) i = 0 j = 0 inversions = 0 counted = False for k in range(p, r+1): if not counted and R[j] < L[i]: inversions += n1 - i counted = True if L[i] <= R[j]: a[k] = L[i] i += 1 else: a[k] = R[j] j += 1 counted = False return inversions if __name__ == '__main__': main()

Leave a Comment