Correctness and the Loop Invariant

  • + 0 comments

    My solution using Python.

    def merge(sorted_list, sublist):
        result = []
        i = j = 0
        
        while i < len(sorted_list) and j < len(sublist):
            if sorted_list[i] < sublist[j]:
                result.append(sorted_list[i])
                i += 1
            else:
                result.append(sublist[j])
                j += 1
                
        result.extend(sorted_list[i:])
        result.extend(sublist[j:])
        return result
    
    def strand_sort(arr):
        if not arr:
            return arr
        
        result = []
        
        while arr:
            i = 0
            sublist = [arr.pop(0)]
            
            while i < len(arr):
                if arr[i] > sublist[-1]:
                    sublist.append(arr.pop(i))
                else:
                    i += 1
            
            result = merge(result, sublist)
        
        return result
    
    m = int(input().strip())
    ar = [int(i) for i in input().strip().split()]
    
    sorted_ar = strand_sort(ar)
    
    print(" ".join(map(str, sorted_ar)))