Problem:
Quick Sort Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode: Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4     do if A[j] <= x
5        then i = i+1
6            exchange A[i] and A[j] 
7 exchange A[i+1] and A[r]
8 return i+1


Quicksort(A, p, r)
1 if p < r
2    then q = Partition(A, p, r)
3        run Quicksort(A, p, q-1)
4        run Quicksort(A, q+1, r) Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers. Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance). Input The first line contains an integer n , the number of cards.  n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space. Output In the first line, print the stability (" Stable " or " Not stable ") of this output. In the following lines, print the arranged cards in the same manner of that of the input. Constraints  1 ≤ n ≤ 100,000  1 ≤ the number of a card  ≤ 10 9  There are no identical card in the input  Sample Input 1 6
D 3
H 2
D 1
S 3
D 2
C 1 Sample Output 1 Not stable
D 1
C 1
D 2
H 2
D 3
S 3 Sample Input 2 2
S 1
H 1 Sample Output 2 Stable
S 1
H 1

Solution (Python):
sentinel = str(10**9+1)

def partition(A, p, r):
    x = int(A[r][1])
    i = p - 1
    for j in range(p, r):
        if int(A[j][1]) <= x:
            i = i + 1
            A[i], A[j] = A[j], A[i]

    A[i+1], A[r] = A[r], A[i+1]
    return i + 1

def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quick_sort(A, p, q-1)
        quick_sort(A, q+1, r)

def merge(lst,left,middle,right):
    left_lst  =  lst[left:middle] + [['',sentinel]]
    right_lst = lst[middle:right] + [['',sentinel]]

    i,j = 0,0
    for k in range(left,right):
        if int(left_lst[i][1]) <= int(right_lst[j][1]):
            lst[k] = left_lst[i]
            i += 1
        else:
            lst[k] = right_lst[j]
            j += 1

def merge_sort(lst,left,right):
    if left+1 < right:
        middle = (left+right)//2
        merge_sort(lst,left,middle)
        merge_sort(lst,middle,right)
        merge(lst,left,middle,right)


n = int(input())
n_lst = [[i for i in input().split()] for _ in range(n)]
m_lst = list(n_lst)
quick_sort(n_lst,0,n-1)
merge_sort(m_lst,0,n)
print('Stable' if n_lst == m_lst else 'Not stable')
for ans in n_lst:
    print('{} {}'.format(ans[0],ans[1]))

Solution (Python):
sentinel = str(10**9+1)

def partition(A, p, r):
    x = int(A[r][1])
    i = p - 1
    for j in range(p, r):
        if int(A[j][1]) <= x:
            i = i + 1
            A[i], A[j] = A[j], A[i]

    A[i+1], A[r] = A[r], A[i+1]
    return i + 1

def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quick_sort(A, p, q-1)
        quick_sort(A, q+1, r)

def merge(lst,left,middle,right):
    left_lst  =  lst[left:middle] + [['',sentinel]]
    right_lst = lst[middle:right] + [['',sentinel]]

    i,j = 0,0
    for k in range(left,right):
        if int(left_lst[i][1]) <= int(right_lst[j][1]):
            lst[k] = left_lst[i]
            i += 1
        else:
            lst[k] = right_lst[j]
            j += 1

def merge_sort(lst,left,right):
    if left+1 < right:
        middle = (left+right)//2
        merge_sort(lst,left,middle)
        merge_sort(lst,middle,right)
        merge(lst,left,middle,right)


n = int(input())
n_lst = [[i for i in input().split()] for _ in range(n)]
m_lst = list(n_lst)
quick_sort(n_lst,0,n-1)
merge_sort(m_lst,0,n)
print('Stable' if n_lst == m_lst else 'Not stable')
for ans in n_lst:
    print('{} {}'.format(ans[0],ans[1]))

Solution (Python):
n = int(input())
data = list(input().split() for _ in range(n))
c = 0

for k in range(n):
    data[k].append(str(k))


def exchange(a, i, j):
    tmp = a[i]
    a[i] = a[j]
    a[j] = tmp
    return a


def partition(a, p, r):
    x = int(a[r][1])
    i = p-1
    for j in range(p, r):
        if int(a[j][1]) <= x:
            i += 1
            a = exchange(a, i, j)
    exchange(a, i+1, r)
    return i+1


def quicksort(a, p, r):
    if p < r:
        q = partition(a, p, r)
        quicksort(a, p, q-1)
        quicksort(a, q+1, r)


quicksort(data, 0, n-1)

for l in range(n-1):
    if int(data[l][1]) == int(data[l+1][1]):
        if int(data[l][2]) > int(data[l+1][2]):
            print('Not stable')
            c = 1
            break

if c == 0:
    print('Stable')

for l in range(n):
    print(data[l][0], data[l][1])

Solution (Python):
import copy
 
INF = 10000000000
def merge(A, left, mid, right):
    count = 0
    L = A[left:mid] + [(INF,INF)]
    R = A[mid:right] + [(INF,INF)]
     
    i, j = 0, 0
    for k in range(left, right):
        count = count + 1
        if L[i][1] <= R[j][1]:
            A[k] = L[i]
            i = i + 1
        else:
            A[k] = R[j]
            j = j + 1
    return count
 
def mergeSort(A, left, right):
    if left + 1 < right:
        mid = (left + right) // 2
        countL = mergeSort(A, left, mid)
        countR = mergeSort(A, mid, right)
        return merge(A, left, mid, right) + countL + countR
    return 0
def partition(a,p,r):
    x=a[r][1]
    i=p-1
    for j in range(p,r):
        if a[j][1]<=x:
            i+=1
            a[i],a[j]=a[j],a[i]
    a[i+1],a[r]=a[r],a[i+1]
    return i+1
def quickSort(a,p,r):
    if p<r:
        q=partition(a,p,r)
        quickSort(a,p,q-1)
        quickSort(a,q+1,r)
n = int(input())
A = [None for i in range(n)]
for i in range(n):
    a, b = input().split()
    A[i] = (a, int(b))

B = copy.deepcopy(A)
quickSort(A, 0, n-1)
mergeSort(B, 0, n)
if A == B:
    print("Stable")
else:
    print("Not stable")
ans = [str(x[0]) +" "+str(x[1]) for x in A]
ans = '\n'.join(ans)
print(ans)

Solution (Python):
a = []
b = {}
n = int(input())
for _ in range(n):
    s, i = input().split()
    a += [(s, int(i))]
    b.setdefault(int(i), []).append(s)
b = {val: iter(s).__next__ for val, s in b.items()}

def partition(a, left, right):
    standard = a[right][1]
    cnt = left
    for i in range(left, right):
        if a[i][1] <= standard:
            a[cnt],a[i] = a[i], a[cnt]
            cnt += 1
    a[cnt],a[right] = a[right], a[cnt]
    return cnt

def quickSort(a, left = 0, right = len(a) - 1):
    if 1 <= right - left:
        cnt_ = partition(a, left, right)
        quickSort(a,left, cnt_ - 1)
        quickSort(a,cnt_ + 1, right)

quickSort(a, 0 , len(a)-1)

ok = 1
for s, i in a:
    if b[i]() != s:
        ok = 0
print(['Not stable','Stable'][ok])


for i in range(n):
    print(*a[i])

Solution (Python):
from copy import deepcopy

def Partition(A, p, r):
    x = A[r][1]
    i = p-1
    for j in range(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i+1], A[r] = A[r], A[i+1]
    return i+1

def Quicksort(A, p, r):
    if p < r:
        q = Partition(A, p, r)
        Quicksort(A, p, q-1)
        Quicksort(A, q+1, r)


n = int(input())
cards = []
for i in range(n):
    card = input().split()
    card[1] = int(card[1])
    cards.append(card)
prev_cards = deepcopy(cards)
prev_cards.sort(key=lambda card: card[1])

Quicksort(cards, 0, n-1)

if cards == prev_cards:
    print("Stable")
else:
    print("Not stable")

for card in cards:
    print(' '.join(map(str, card)))

Solution (Python):
def q(a,l,r):
    if l>=r:return
    i=l
    for j in range(l,r):
        if int(a[j][2:])<=int(a[r][2:]):
            a[i],a[j]=a[j],a[i]
            i+=1
    a[i],a[r]=a[r],a[i]
    q(a,l,i-1)
    q(a,i+1,r)

n=input()
a=[raw_input() for _ in range(n)]
b=a[:]
q(b,0,len(b)-1)
n=0
print "Stable" if b==sorted(a,key=lambda i:int(i[2:])) else "Not stable"
for i in b:print i

Solution (Python):
def partition(a, p, r):
    q  = p
    for i in range(p, r):
        if a[i][1] <= a[r][1]:
            a[q], a[i] = a[i], a[q]
            q += 1
    a[q], a[r] = a[r], a[q]
    return q 
  
def quicksort(a, p, r):
    if p < r:
        q = partition(a, p, r)
        quicksort(a, p, q-1)
        quicksort(a, q+1, r)
  
def check_stable(a):
    for i in range(1, len(a)):
        if a[i - 1][1] == a[i][1]:
            if a[i - 1][2] > a[i][2]:
                return 'Not stable'
    return 'Stable'
      
import sys
n = int(sys.stdin.readline())
a = []
for i in range(n):
    suit, num = sys.stdin.readline().split()
    a += [[suit, int(num), i]]
  
quicksort(a, 0, len(a) - 1)
print(check_stable(a))
  
for line in a:
    print(line[0],line[1])

Solution (Python):
from collections import defaultdict
def partition(A, p, r):
    x = A[r][1]
    i = p - 1
    for j in xrange(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i+1], A[r] = A[r], A[i+1]
    return i + 1


def quickSort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q-1)
        quickSort(A, q+1, r)

def getMarkOrder(A):
    d = defaultdict(list)
    for x in A:
        d[x[1]].append(x[0])
    return d

n = int(raw_input())
A = []
for i in xrange(n):
    X = raw_input().split()
    A.append((X[0], int(X[1])))
B = getMarkOrder(A)
quickSort(A, 0, n-1)
C = getMarkOrder(A)
print 'Stable' if B == C else 'Not stable'
for x in A:
    print x[0], x[1]

Solution (Python):
def partition(a, p, r):
    x = a[r][1]
    i = p - 1
    for j in range(p, r):
        if a[j][1] <= x:
            i = i + 1
            a[i], a[j] = a[j], a[i]
    a[i + 1], a[r] = a[r], a[i + 1]
    return i + 1


def quicksort(a, p, r):
    if p < r:
        q = partition(a, p, r)
        quicksort(a, p, q - 1)
        quicksort(a, q + 1, r)


def checkstable(a):
    for i in range(1, len(a)):
        if a[i - 1][1] == a[i][1]:
            if a[i - 1][2] > a[i][2]:
                return "Not stable"
    return "Stable"


import sys
n = int(input())
a = []
for i in range(n):
    suit, num = sys.stdin.readline().split()
    a += [[suit, int(num), i]]

quicksort(a, 0, len(a) - 1)
print(checkstable(a))

for line in a:
    print(line[0], line[1])

Solution (Python):
def partition(a,p,r):
    x = int(a[r][1])
    i = p - 1
    for j in range(p,r):
        if int(a[j][1]) <= x:
            i += 1
            a[i],a[j] = a[j],a[i]
    a[i+1],a[r] = a[r],a[i+1]
    return i + 1
def quicksort(a,p,r):
    if p < r:
        q = partition(a,p,r)
        quicksort(a,p,q-1)
        quicksort(a,q+1,r)
n = input()
a = [map(str, raw_input().split()) for i in range(n)]
b = a[:]
quicksort(a,0,n-1)
print "Stable" if a == sorted(b, key = lambda x: int(x[1])) else "Not stable"
for s,i in a: print s,i

Solution (Python):
def partition(A, p, r):
  (suite, x) = A[r]
  i = p - 1
  for j in range(p, r):
    if A[j][1] <= x:
      i = i + 1
      A[i], A[j] = A[j], A[i]
  A[i+1], A[r] = A[r], A[i+1]
  return i + 1

def quick_sort(A, p, r):
  if p < r:
    q = partition(A, p, r)
    quick_sort(A, p, q - 1)
    quick_sort(A, q + 1, r)

if __name__ == "__main__":
  import sys
  n = sys.stdin.readline()
  items = []
  suite_order = {}
  for line in sys.stdin:
    item  = line.strip().split()
    items.append(item)
    if item[1] not in suite_order:
      suite_order[item[1]] = []
    suite_order[item[1]].append(item[0])

  items = [ (item[0], int(item[1])) for item in items ]
  quick_sort(items, 0, len(items) - 1)

  is_stable = True
  for item in items:
    if suite_order[str(item[1])][0] != item[0]:
      is_stable = False
    suite_order[str(item[1])].pop(0)
  if is_stable:
    print "Stable"
  else:
    print "Not stable"

  for item in items:
    print "%s %s" % (item[0], str(item[1]))

Solution (Python):
N = int(raw_input())
A, A2 = [], []
for i in range(N):
    a = raw_input().split()
    A.append([a[0], int(a[1])])
    A2.append([a[0], int(a[1])])

def partition(A):
    i = 0
    r = A[-1][1]
    for j in range(0, len(A)):
        if A[j][1] <= r:
            A[i], A[j] = A[j], A[i]
            i += 1
    return i-1, A

def quickSort(A):
    if len(A) < 2:
        return A
    
    q, A = partition(A)
    left = A[:q]
    right = A[q+1:]
    
    A[:q] = quickSort(left)
    A[q+1:] = quickSort(right)
    return A

def merge(left, right):
    global count
    sorted_list = []
    l_index = 0
    r_index = 0

    while l_index < len(left) and r_index < len(right):
        if left[l_index][1] <= right[r_index][1]:
            sorted_list.append(left[l_index])
            l_index += 1
        else:
            sorted_list.append(right[r_index])
            r_index += 1

    if len(left) != l_index:
        sorted_list.extend(left[l_index:])
    if len(right) != r_index:
        sorted_list.extend(right[r_index:])

    return sorted_list 

def mergeSort(A):
    
    if len(A) <= 1:
        return A

    mid = len(A) // 2
    left = A[:mid]
    right = A[mid:]

    left = mergeSort(left)
    right = mergeSort(right)

    return list(merge(left, right))

A = quickSort(A)
if A == mergeSort(A2):
    print "Stable"
else:
    print "Not stable"
for w, i in A:
    print w,i

Solution (Python):
def partition(data, left, right):
    pivot = int(data[right][2:])
    i = left - 1
    for j in range(left, right):
        if int(data[j][2:]) <= pivot:
            i += 1
            data[i], data[j] = data[j], data[i]
    data[i+1], data[right] = data[right], data[i+1]
    return i+1

def quick_sort(data, left, right):
    if left < right:
        new_pivot = partition(data, left, right)
        quick_sort(data, left, new_pivot-1)
        quick_sort(data, new_pivot+1, right)


def merge(data, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = data[left : mid]
    R = data[mid : right]
    L.append("  10000000000")
    R.append("  10000000000")
    i = 0
    j = 0
    for k in range(left, right):
        if int(L[i][2:]) <= int(R[j][2:]):
            data[k] = L[i]
            i += 1
        else:
            data[k] = R[j]
            j += 1

def merge_sort(data, left, right):
    if left + 1 < right:
        mid = (left + right) / 2
        merge_sort(data, left, mid)
        merge_sort(data, mid, right)
        merge(data, left, mid, right)

def main():
    num = raw_input()
    pairs_quick = []
    pairs_check = []
    for i in range(int(num)):
        pair = raw_input()
        pairs_quick.append(pair)
        pairs_check.append(pair)
    
    quick_sort(pairs_quick, 0, int(num)-1)
    merge_sort(pairs_check, 0, int(num))
    if pairs_quick == pairs_check:
        print "Stable"
    else:
        print "Not stable"

    print "\n".join(pairs_quick)
    

if __name__ == "__main__":
    main()

Solution (Python):
def partition(data, left, right):
    pivot = int(data[right][2:])
    i = left - 1
    for j in range(left, right):
        if int(data[j][2:]) <= pivot:
            i += 1
            data[i], data[j] = data[j], data[i]
    data[i+1], data[right] = data[right], data[i+1]
    return i+1

def quick_sort(data, left, right):
    if left < right:
        new_pivot = partition(data, left, right)
        quick_sort(data, left, new_pivot-1)
        quick_sort(data, new_pivot+1, right)

def main():
    num = raw_input()
    pairs_quick = []
    pairs_check = []
    for i in range(int(num)):
        pair = raw_input()
        pairs_quick.append(pair)
        pairs_check.append(pair)
    
    quick_sort(pairs_quick, 0, int(num)-1)
    pairs_check = sorted(pairs_check, key = lambda i:int(i[2:]))
    if pairs_quick == pairs_check:
        print "Stable"
    else:
        print "Not stable"

    print "\n".join(pairs_quick)

if __name__ == "__main__":
    main()

Solution (Python):
def partition(a,p,r):
    x=int(a[r][1:])
    i=p-1
    for j in range(p,r):
        if(int(a[j][1:])<=x):
            i+=1
            a[i],a[j]=a[j],a[i]
    a[i+1],a[r]=a[r],a[i+1]
    return i+1

def quicksort(a,p,r):
    if(p<r):
        q=partition(a,p,r)
        quicksort(a,p,q-1)
        quicksort(a,q+1,r)

a=[]
n=int(input())
for i in range(n):
    s=input()
    a.append("".join(s.split()))

c=list(a)
quicksort(c,0,n-1)

d=dict()
i=0
x="-1"
for i in c:
    if(x!=i[1:]):
        d[i[1:]]=[i[:1]]
        x=i[1:]
    else:
        d[x].append(i[:1])

message="Stable"

for i in reversed(a):
    if(i[1:] in d):
        if(d[i[1:]].pop()!=i[:1]):
            message="Not stable"
            break

print(message)

for i in c:
    print("%s %s"%(i[:1],i[1:]))

Solution (Python):
def Partition(A,p,r):
    x = A[r]
    i = p-1
    for j in range(p,r):
        if (A[j] <= x):
            i += 1
            A[i],A[j] = A[j],A[i]
    A[i+1],A[r] = A[r],A[i+1]
    return i+1

def qsort(A,p,r):
    if p < r:
        q = Partition(A,p,r)
        qsort(A,p,q-1)
        qsort(A,q+1,r)

def marge(A,left,mid,right):
    n1 = mid -left
    n2 = right -mid
    L = []
    R = []
    for i in range(left,n1+left):
        L.append(A[i])
    for i in range(mid,n2+mid):
        R.append(A[i])
 
    L.append(card('S 10000000000'))
    R.append(card('S 10000000000'))
 
    r_id,l_id = 0,0
    for k in range(left,right):
        if(L[l_id] <= R[r_id]):
            A[k] = L[l_id]
            l_id += 1
        else:
            A[k] = R[r_id]
            r_id += 1
 
def margeSort(A,left,right):
    if left+1 < right:
        mid = int((left+right)/2)
        margeSort(A,left,mid)
        margeSort(A,mid,right)
        marge(A,left,mid,right)


class card(object):
    def __init__(self, str):
        data = str.split()
        self.symbol,self.num = data[0],int(data[1])
    
    def __le__(self,obj):
        if(self.num <= obj.num):
            return True
        else:
            return False
    def __ge__(self,obj):
        if(self.num >= obj.num):
            return True
        else:
            return False

    def display_card(self):
        print("{0} {1}".format(self.symbol,self.num))

c = []        
n = int(input())
while(n>0):
    c.append(card(input()))
    n -= 1
c_marge = c.copy()
margeSort(c_marge,0,len(c))

qsort(c,0,len(c)-1)

'''
notStable = False
for i in range(1,len(c)):
    if(c[i-1].num == c[i].num):
        firstCard = c[i-1]
        secondCard = c[i]
        is_found_1st = False
        is_found_2nd = False

        for org in c_org:
            if(org == firstCard):
                is_found_1st = True
            if(org == secondCard):
                is_found_2nd = True
                if(is_found_1st == True):
                    break
                else:
                    notStable = True
                    break
if(notstable == 1):
    print('Not stable')
else:
    print('Stable')
for x in c:
    x.display_card()
'''

is_stable = True
for i in range(0,len(c)):
    if(c[i] != c_marge[i]):
        is_stable = False
        break
if(is_stable == True):
    print('Stable')
else:
    print('Not stable')
for i in c:
    i.display_card()

Solution (Python):
def mergesort(A, left, right):
 
    if left + 1 < right:
        mid = (left + right)/2
         
        mergesort(A, left, mid)
        mergesort(A, mid, right)
        merge(A, left, mid, right)
 
 
def merge(A, left, mid, right):

    n1 = mid -left
    n2 = right - mid
    L = []
    R = []
    x = "  10000000000"
    for i in range(0, n1):
        L.append(A[left + i])
    for i in range(0, n2):
        R.append(A[mid + i])
    L.append(x)
    R.append(x)
    i = 0
    j = 0
    for k in range(left, right):
        if int(L[i][2:]) <= int(R[j][2:]):
            A[k] = L[i]
            i = i + 1
        else:
            A[k] = R[j]
            j = j + 1
            
            
def partition(A, p, r):
    x = int(A[r-1][2:])
    i = p - 1
    for j in range(p, r-1):
        if int(A[j][2:]) <= x:
            i = i + 1
            A[i],A[j]=A[j], A[i]
             
    A[i+1], A[r-1]=A[r-1], A[i+1]
    return i+1
 
def quicksort(A, p, r):
    if p < r-1:
        q = partition(A, p, r)
         
        quicksort(A, p, q)
        quicksort(A, q+1, r)
 
 
 
 
if __name__ == "__main__":
    num = int(raw_input())
    num_list = []
    num_list1 = []
    for i in range(num):
        num_list.append(raw_input())
    num_list1 = list(num_list)
    quicksort(num_list, 0, len(num_list))
  
    mergesort(num_list1, 0, len(num_list1))
     
    if num_list == num_list1:
        print ("Stable")
    else:
        print ("Not stable")
    print "\n".join(num_list)

Solution (Python):
import copy

n = int(raw_input())
cards = []
for i in range(n):
    suit,num = raw_input().strip().split(' ')
    num = int(num)
    cards.append((suit,num))

def quick_sort(S,p,r):
    if p < r:
        q = partition(S,p,r)
        quick_sort(S,p,q-1)
        quick_sort(S,q+1,r)

def partition(S,p,r):
    x = S[r][1]
    i = p-1
    for j in range(p,r):
        if S[j][1] <= x:
            i += 1
            S[j],S[i]=S[i],S[j]
    S[r],S[i+1]=S[i+1],S[r]
    return i+1

def merge_sort(S):
    if len(S) <= 1:
        return S
    S1,S2 = split(S)
    return merge(merge_sort(S1),merge_sort(S2))

def split(S):
    mid = len(S)/2
    return S[:mid],S[mid:]

def merge(S1,S2):
    S = []
    S1.append(('SENTINEL',100000000000))
    S2.append(('SENTINEL',100000000000))
    i = 0
    j = 0
    for k in range(len(S1)+len(S2)-2):
        if S1[i][1] <= S2[j][1]:
            S.append(S1[i])
            i += 1
        else:
            S.append(S2[j])
            j += 1
    return S



cards2 = copy.copy(cards)
quick_sort(cards,0,len(cards)-1)
cards2 = merge_sort(cards2)
flag = True
for i in range(len(cards)):
    if cards[i] != cards2[i]:
        print "Not stable"
        flag = False
        break
if flag: print "Stable"
for suit,num in cards:
    print suit,num

Solution (Python):
def make_card(i, card):
    suit, value = card.split()
    return (int(value), i, card)


def partition_stable(a, p, r):
    x, i = a[r], p - 1
    for j in range(p, r):
        if a[j] <= x:
            i += 1
            a[i], a[j] = a[j], a[i]
    i += 1
    a[i], a[r] = a[r], a[i]
    return i


def partition_not_stable(a, p, r):
    x, i = a[r][0], p - 1
    for j in range(p, r):
        if a[j][0] <= x:
            i += 1
            a[i], a[j] = a[j], a[i]
    i += 1
    a[i], a[r] = a[r], a[i]
    return i


def quick_sort(a, p, r, func):
    if p < r:
        q = func(a, p, r)
        quick_sort(a, p, q - 1, func)
        quick_sort(a, q + 1, r, func)


n = int(input())
a = list(make_card(i, input()) for i in range(n))
b = a[:]

quick_sort(a, 0, n - 1, partition_not_stable)
quick_sort(b, 0, n - 1, partition_stable)
print(('S' if a == b else 'Not s') + 'table')
print('\n'.join(card[2] for card in a))

Solution (Python):


def partition(A, p, r):
    x = int(A[r][1])
    i = p - 1
    for j in range(p, r):
        if int(A[j][1]) <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1

def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quick_sort(A, p, q - 1)
        quick_sort(A, q + 1, r)
    return A

class CheckStable:
    def __init__(self):
        self.d = dict() 

    def store_cards(self, cards):
        for i in range(n):
            if cards[i][1] in self.d:
                self.d[cards[i][1]].append(cards[i][0])
            else:
                self.d[cards[i][1]] = [cards[i][0]]

    def is_stable(self, cards):
        for item in reversed(cards):
            if self.d[item[1]].pop() != item[0]:
                return "Not stable"
        return "Stable"

n = int(input())
cards = [tuple(input().split()) for i in range(n)]
d = CheckStable()
d.store_cards(cards)

quick_sort(cards, 0, n - 1)

print(d.is_stable(cards))
for i in range(n):
    print(' '.join(cards[i]))

Solution (Python):
"""Quick Sort."""

def partition(A, p, r):
    """Divide list A into A[p:q] whose elements aren't greater than A[q] and
    A[q+1:r] whose elements are greater than A[q].

    Each element of A is a list [x, y].
    x is a character of S, H, C or D (trump suits).
    y is a natural number.
    
    Default value of p is 0.
    The number as a refernce of the division is A[r].
    
    Return the index q.
    """

    x = A[r][1]
    i = p - 1
    for j in range(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1


def quickSort(A, p, r):
    """Sort list A in ascending order with quick sort algorithm.

    Default value of p is 0 (the start index).
    r is 1 less than the length of A (the last index of A).
    """

    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q - 1)
        quickSort(A, q + 1, r)


def is_stable(A, B):
    """Check the stability of sorted list A.

    A is a sorted list.
    B is a original list.

    Return True or False.
    """

    cA = list(A)
    for x in B:
        i = cA.index(x)
        if i == 0:
            pass
        elif cA[i - 1][1] == x[1]:
            return False
        del cA[i]
    return True



import sys

r = int(sys.stdin.readline()) - 1

A = [x.split() for x in sys.stdin.readlines()]

for i, x in enumerate(A):
    A[i][1] = int(x[1])

B = list (A)

quickSort(A, 0, r)

if is_stable(A, B):
    print('Stable')
else:
    print('Not stable')

for x in A:
    print(*x)

Solution (Python):
"""Quick Sort."""

def partition(A, p, r):
    """Divide list A into A[p:q] whose elements aren't greater than A[q] and
    A[q+1:r] whose elements are greater than A[q].

    Each element of A is a list [x, y].
    x is a character of S, H, C or D (trump suits).
    y is a natural number.
    Sorting is done based on y numbers.
    
    Default value of p is 0.
    The number as a refernce of the division is A[r].
    
    Return the index q.
    """

    x = A[r][1]
    i = p - 1
    for j in range(p, r):
        if A[j][1] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1


def quickSort(A, p, r):
    """Sort list A in ascending order with quick sort algorithm.

    Default value of p is 0 (the start index).
    r is 1 less than the length of A (the last index of A).
    """

    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q - 1)
        quickSort(A, q + 1, r)


def is_stable(A, B):
    """Check the stability of sorted list A.

    A is a sorted list.
    B is a original list.

    Return True or False.
    """

    cA = list(A)
    for x in B:
        i = cA.index(x)
        if i == 0:
            pass
        elif cA[i - 1][1] == x[1]:
            return False
        del cA[i]
    return True



import sys

r = int(sys.stdin.readline()) - 1

A = []

for x in sys.stdin.readlines():
    suit, num = x.split()
    num = int(num)
    A.append([suit, num])

B = list (A)

quickSort(A, 0, r)

if is_stable(A, B):
    print('Stable')
else:
    print('Not stable')

for x in A:
    print(*x)

Solution (Python):
class Quicksort:
    def quicksort(self, a, p, r):
        if p < r:
            q = self.partion(a, p, r)
            self.quicksort(a, p, q - 1)
            self.quicksort(a, q + 1, r)
        return(a)

    def partion(self, a, p, r): 
        x = a[r][1]
        i = p - 1
        for j in range(p, r):
            if a[j][1] <= x:
                i += 1
                a[i], a[j] = a[j], a[i]
        a[i + 1], a[r] = a[r], a[i + 1]
        return(i+1)

def bubbleSort(a, n):
    flag = 1
    while flag == 1:
        flag = 0
        for j in range(n-1, 0, -1):
            if a[j][1] < a[j - 1][1]:
                a[j], a[j-1] = a[j-1], a[j]
                flag = 1
    return(a)

if __name__ == '__main__':
    n = int(input().rstrip())
    cards = []
    for i in range(n):
        tmp = input().rstrip().split(" ")
        tmp[1] = int(tmp[1])
        cards.append(tmp)
    a = cards[:]
    b = cards[:]
    x = Quicksort()
    a = x.quicksort(a, 0, n-1)
    b = sorted(b, key=lambda i: i[1])
    
    if a == b:
        print("Stable")
    else:
        print("Not stable")
    
    for i in a:
        i[1] = str(i[1])
        print(" ".join(i))

Solution (Python):
n = int(raw_input())
stable = 1

class Card():
    __slots__ = ('suit', 'value')


A = [Card() for _ in xrange(n)]

B = [Card() for _ in xrange(n)]

for i in xrange(n):
    a = raw_input().split()
    A[i].suit = a[0]
    B[i].suit = a[0]
    A[i].value = int(a[1])
    B[i].value = int(a[1])

def merge(A, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = [0] * (n1+1) 
    R = [0] * (n2+1)
    L[:n1] = A[left:mid]
    R[:n2] = A[mid:right]
    
    
    
    
    L[n1] = Card()
    R[n2] = Card()
    L[n1].value = float('inf')
    R[n2].value = float('inf')
    i = 0
    j = 0
    for k in xrange(left,right):
        if L[i].value <= R[j].value:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    return 0

def mergeSort(A, left, right):
    if right - left > 1:
        mid = int((left + right) / 2)
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)
    return 0

def partition(A, p, r):
    x = A[r].value
    i = p-1
    for j in xrange(p,r):
        if A[j].value <= x:
            i += 1
            tmp = A[i]
            A[i] = A[j]
            A[j] = tmp
    tmp = A[i+1]
    A[i+1] = A[r]
    A[r] = tmp
    return i+1

def quickSort(A,p,r):
    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q-1)
        quickSort(A, q, r)
    return 0

mergeSort(A, 0, n)
quickSort(B, 0, n-1)

for i in xrange(n):
    if A[i].suit != B[i].suit:
        stable = 0

if stable == 1:
    print 'Stable'
else:
    print 'Not stable'

for i in xrange(n):
    print B[i].suit, B[i].value

Solution (Python):
n = int(raw_input())


class Card():
    __slots__ = ('suit', 'value')


A = [Card() for _ in xrange(n)]

B = [Card() for _ in xrange(n)]

s = set()
for i in xrange(n):
    a = raw_input().split()
    A[i].suit = a[0]
    B[i].suit = a[0]
    A[i].value = int(a[1])
    B[i].value = int(a[1])
    s.add(int(a[1]))
'''
def merge(A, left, mid, right):
    n1 = mid - left
    n2 = right - mid
    L = [0] * (n1+1) 
    R = [0] * (n2+1)
    L[:n1] = A[left:mid]
    R[:n2] = A[mid:right]
    
    
    
    
    L[n1] = Card()
    R[n2] = Card()
    L[n1].value = float('inf')
    R[n2].value = float('inf')
    i = 0
    j = 0
    for k in xrange(left,right):
        if L[i].value <= R[j].value:
            A[k] = L[i]
            i += 1
        else:
            A[k] = R[j]
            j += 1
    return 0

def mergeSort(A, left, right):
    if right - left > 1:
        mid = int((left + right) / 2)
        mergeSort(A, left, mid)
        mergeSort(A, mid, right)
        merge(A, left, mid, right)
    return 0
'''
def partition(A, p, r):
    x = A[r].value
    i = p-1
    for j in xrange(p,r):
        if A[j].value <= x:
            i += 1
            tmp = A[i]
            A[i] = A[j]
            A[j] = tmp
    tmp = A[i+1]
    A[i+1] = A[r]
    A[r] = tmp
    return i+1

def quickSort(A,p,r):
    if p < r:
        q = partition(A, p, r)
        quickSort(A, p, q-1)
        quickSort(A, q, r)
    return 0


quickSort(B, 0, n-1)

for i in s:
    if [d.suit for d in A if d.value == i] != [d.suit for d in B if d.value == i]:
        print('Not stable')
        break
else:
    print('Stable')




for i in xrange(n):
    print B[i].suit, B[i].value