├── Sorting Visualization ├── requirements.txt ├── README.md ├── QuickSort.py └── sorting.py ├── Insertion_Sort.py ├── Selection_Sort.py ├── Quick_Sort.py ├── Merge_Sort.py └── README.md /Sorting Visualization/requirements.txt: -------------------------------------------------------------------------------- 1 | pygame 2 | matplotlib 3 | -------------------------------------------------------------------------------- /Insertion_Sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(InputList): 2 | for i in range(1, len(InputList)): 3 | j = i-1 4 | nxt_element = InputList[i] 5 | # Compare the current element with next one 6 | 7 | while (InputList[j] > nxt_element) and (j >= 0): 8 | InputList[j+1] = InputList[j] 9 | j=j-1 10 | InputList[j+1] = nxt_element 11 | # you can add list of any numbers 12 | list = [6,5,3,1,8,7,2,4] 13 | insertion_sort(list) 14 | print(list) -------------------------------------------------------------------------------- /Selection_Sort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(input_list): 2 | 3 | for idx in range(len(input_list)): 4 | 5 | min_idx = idx 6 | for j in range( idx +1, len(input_list)): 7 | if input_list[min_idx] > input_list[j]: 8 | min_idx = j 9 | # Swap the minimum value with the compared value 10 | 11 | input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx] 12 | 13 | # add any list of number here 14 | l = [5,2,4,6,1,3] 15 | selection_sort(l) 16 | print(l) 17 | -------------------------------------------------------------------------------- /Quick_Sort.py: -------------------------------------------------------------------------------- 1 | def partition(arr, low, high): 2 | i = (low-1) # index of smaller element 3 | pivot = arr[high] # pivot 4 | 5 | for j in range(low, high): 6 | 7 | # If current element is smaller than or 8 | # equal to pivot 9 | if arr[j] <= pivot: 10 | 11 | # increment index of smaller element 12 | i = i+1 13 | arr[i], arr[j] = arr[j], arr[i] 14 | 15 | arr[i+1], arr[high] = arr[high], arr[i+1] 16 | return (i+1) 17 | 18 | def quickSort(arr, low, high): 19 | if len(arr) == 1: 20 | return arr 21 | if low < high: 22 | 23 | pi = partition(arr, low, high) 24 | quickSort(arr, low, pi-1) 25 | quickSort(arr, pi+1, high) 26 | 27 | arr = [6,5,4,1,8,7,3,4] 28 | n = len(arr) 29 | quickSort(arr, 0, n-1) 30 | print(arr) 31 | -------------------------------------------------------------------------------- /Merge_Sort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(unsorted_list): 2 | if len(unsorted_list) <= 1: 3 | return unsorted_list 4 | # Find the middle point and divide the unsorted list 5 | middle = len(unsorted_list) // 2 6 | left_list = unsorted_list[:middle] 7 | right_list = unsorted_list[middle:] 8 | 9 | left_list = merge_sort(left_list) 10 | right_list = merge_sort(right_list) 11 | return list(merge(left_list, right_list)) 12 | 13 | # Merge the sorted halves 14 | 15 | def merge(left_half,right_half): 16 | 17 | res = [] 18 | while len(left_half) != 0 and len(right_half) != 0: 19 | if left_half[0] < right_half[0]: 20 | res.append(left_half[0]) 21 | del left_half[0] 22 | else: 23 | res.append(right_half[0]) 24 | del right_half[0] 25 | if len(left_half) == 0: 26 | res = res + right_half 27 | else: 28 | res = res + left_half 29 | return res 30 | # You can add any list of numbers here 31 | unsorted_list = [6,5,3,1,8,7,2,4] 32 | 33 | print(merge_sort(unsorted_list)) 34 | 35 | -------------------------------------------------------------------------------- /Sorting Visualization/README.md: -------------------------------------------------------------------------------- 1 | ## Sorting Visualization 2 | 3 | ![]() 4 | ![]() 5 | ![]() 6 | ![]() 7 | ![]() 8 | 9 | There are various types of sorting algorithms and it is very difficult to understand their working without visualization. 10 | Hence we decided to visualize these sorting algos in python with the help of matplotlib.animations 11 | 12 | Pro tip :- Time complexity can also be seen through these visualizations 13 | 14 | ## Introduction 15 | 16 | This repository is a demo of visualizing 8 types of Sorting Algorithms. It aims to make Sorting Algorithms easier for programmers to understand. Also, you can see the difference of Time Complexity between different sorting algorithms. 17 | 18 | | Sorting Algorithm | AverageTime Complexity | Bad Time Complexity | Stability | 19 | | ----------------- | ---------------------- | ------------------- | --------- | 20 | | Bubble Sort | O(N^2) | O(N^2) | YES | 21 | | Insertion Sort | O(N^2) | O(N^2) | YES | 22 | | Shell Sort | O(N^5/4) | O(N^2) | NO | 23 | | Selection Sort | O(N^2) | O(n^2) | NO | 24 | | Heapify Sort | O(NlogN) | O(NlogN) | NO | 25 | | Merge Sort | O(NlogN) | O(NlogN) | YES | 26 | | Quick Sort | O(NlogN) | O(N^2) | NO | 27 | | Count Sort | O(N) | O(N) | YES | 28 | 29 | 30 | 31 | ## Dependencies 32 | 33 | - python3.x 34 | - matplotlib 35 | - pygame 36 | 37 | ## Quick Start 38 | 39 | 0. Check all dependencies installed 40 | 41 | This command can help you install all the dependent packages 42 | 43 | `pip install -r requirements.txt` 44 | 45 | 2. Start sorting.py 46 | 47 | `python3 sorting.py` 48 | 49 | - `Enter the number of elements:`: choise a number 50 | - `Choose algorithm:`: Sorting Type. Choose one 51 | 1.Bubble 52 | 2.Insertion 53 | 3.Quick 54 | 4.Selection 55 | 5.Merge Sort 56 | 6.Heapify 57 | 7.Shell 58 | 8.Count sort 59 | 60 | 3. Start sorting.py 61 | 62 | `python3 QuickSort.py` 63 | 64 | - `Press “Enter” key:`: to Perform Visualization. 65 | - `Press “R” key:`: to generate new array. 66 | 67 | #### All sortings are done on randomly generated arrays of size 30. 68 | 69 | ### Bubble Sort 70 | Total operations = 435 71 | 72 | ![bubble](https://f.top4top.io/p_1743devrw1.gif) 73 | 74 | ### Selection Sort 75 | Total operations = 460 76 | 77 | ![selection](https://g.top4top.io/p_1743jlpcp2.gif) 78 | 79 | ### Insertion Sort 80 | Total operations = 230 81 | 82 | ![Insertion](https://h.top4top.io/p_1743xxqrn3.gif) 83 | 84 | ### Quick Sort 85 | Total operations = 131 86 | 87 | ![quick](https://i.top4top.io/p_1743rf4xy4.gif) 88 | 89 | another sorting algorithm visualization using pygame 90 | 91 | ![quick](https://i.top4top.io/p_1743ghv4d1.png) 92 | ### Merge Sort 93 | Total operations = 177 94 | 95 | ![merge](https://j.top4top.io/p_1743bj4815.gif) 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Welcome to Sorting-Algorithm Repository! 2 | 3 | 4 | **Sorting** is a skill that every **software engineer** and **developer** needs some knowledge of. Not only to pass coding interviews but as a general understanding of programming itself. The different sorting algorithms are a perfect showcase of how algorithm design can have such a strong effect on program complexity, speed, and efficiency. 5 | 6 | 7 | # Selection Sort 8 | 9 | **Selection sort** is also quite simple but frequently outperforms bubble sort. If you are choosing between the two, it’s best to just default right to selection sort. With Selection sort, we divide our input list / array into two parts: the sublist of items already sorted and the sublist of items remaining to be sorted that make up the rest of the list. We first find the smallest element in the unsorted sublist and place it at the end of the sorted sublist. Thus, we are continuously grabbing the smallest unsorted element and placing it in sorted order in the sorted sublist. This process continues iteratively until the list is fully sorted. 10 | ![enter image description here](https://a.top4top.io/p_1741bco6x1.gif) 11 | 12 | 13 | > to see the code open/run Selection_Sort.py 14 | > Python3 Selection_Sort.py 15 | 16 | ## Insertion Sort 17 | 18 | Insertion sort is both faster and well-arguably more simplistic than both bubble sort and selection sort. Funny enough, it’s how many people sort their cards when playing a card game! On each loop iteration, insertion sort removes one element from the array. It then finds the location where that element belongs within another _sorted_ array and inserts it there. It repeats this process until no input elements remain. 19 | ![enter image description here](https://c.top4top.io/p_1741u2v4h1.gif) 20 | 21 | > to see the code open/run Insertion_Sort.py 22 | > Python3 Insertion_Sort.py 23 | 24 | ## Merge Sort 25 | Merge sort is a perfectly elegant example of a Divide and Conquer algorithm. It simple uses the 2 main steps of such an algorithm: 26 | 27 | (1) Continuously _divide_ the unsorted list until you have _N_ sublists, where each sublist has 1 element that is “unsorted” and _N_ is the number of elements in the original array. 28 | 29 | (2) Repeatedly [merge](https://en.wikipedia.org/wiki/Merge_algorithm) i.e _conquer_ the sublists together 2 at a time to produce new sorted sublists until all elements have been fully merged into a single sorted array. 30 | ![enter image description here](https://f.top4top.io/p_1741h1u631.gif) 31 | 32 | > > to see the code open/run Merge_Sort.py 33 | > > Python3 Merge_Sort.py 34 | 35 | ## Quick Sort 36 | 37 | Like [Merge Sort](https://en.wikipedia.org/wiki/Merge_algorithm), **QuickSort** is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. 38 | 39 | 1. Always pick first element as pivot. 40 | 2. Always pick last element as pivot (implemented below) 41 | 3. Pick a random element as pivot. 42 | 4. Pick median as pivot. 43 | 44 | The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time. 45 | ![enter image description here](https://f.top4top.io/p_1741h1u631.gif) 46 | > > to see the code open/run Quick_Sort.py 47 | > > Python3 Quick_Sort.py 48 | 49 | -------------------------------------------------------------------------------- /Sorting Visualization/QuickSort.py: -------------------------------------------------------------------------------- 1 | # Imports 2 | import pygame 3 | import random 4 | pygame.font.init() 5 | 6 | # Total window 7 | screen = pygame.display.set_mode( 8 | (900, 650) 9 | ) 10 | 11 | # Title and Icon 12 | pygame.display.set_caption("SORTING VISUALISER") 13 | 14 | # Boolean variable to run 15 | # the program in while loop 16 | run = True 17 | 18 | # Window size and some initials 19 | width = 900 20 | length = 600 21 | array =[0]*151 22 | arr_clr =[(0, 204, 102)]*151 23 | clr_ind = 0 24 | clr =[(0, 204, 102), (255, 0, 0), 25 | (31, 133, 153), (157, 102, 255)] 26 | fnt = pygame.font.SysFont("comicsans", 30) 27 | fnt1 = pygame.font.SysFont("comicsans", 20) 28 | 29 | 30 | # Function to generate new Array 31 | def generate_arr(): 32 | for i in range(1, 151): 33 | arr_clr[i]= clr[0] 34 | array[i]= random.randrange(1, 100) 35 | 36 | # Intially generate a array 37 | generate_arr() 38 | 39 | # Function to refill the 40 | # updates on the window 41 | def refill(): 42 | screen.fill((255, 255, 255)) 43 | draw() 44 | pygame.display.update() 45 | pygame.time.delay(30) 46 | 47 | # Sorting Algo:Quick sort 48 | def quicksort(array, l, r): 49 | if l arr[j + 1]): 23 | swap(arr, j, j + 1) 24 | yield arr 25 | def insertion_sort(arr): 26 | if(len(arr)==1): 27 | return 28 | for i in range(1,len(arr)): 29 | j = i 30 | while(j>0 and arr[j-1]>arr[j]): 31 | swap(arr,j,j-1) 32 | j-=1 33 | yield arr 34 | 35 | def quick_Sort(arr,p,q): 36 | if(p>=q): 37 | return 38 | piv = arr[q] 39 | pivindx = p 40 | for i in range(p,q): 41 | if(arr[i]mid): 84 | while(j<=ub): 85 | new.append(arr[j]) 86 | j+=1 87 | else: 88 | while(i<=mid): 89 | new.append(arr[i]) 90 | i+=1 91 | for i,val in enumerate(new): 92 | arr[lb+i] = val 93 | yield arr 94 | 95 | def heapify(arr,n,i): 96 | largest = i 97 | l = i*2+1 98 | r = i*2+2 99 | while(larr[largest]): 100 | largest = l 101 | while(rarr[largest]): 102 | largest = r 103 | if(largest!=i): 104 | swap(arr,i,largest) 105 | yield arr 106 | yield from heapify(arr,n,largest) 107 | 108 | def heap_sort(arr): 109 | n = len(arr) 110 | for i in range(n,-1,-1): 111 | yield from heapify(arr,n,i) 112 | for i in range(n-1,0,-1): 113 | swap(arr,0,i) 114 | yield arr 115 | yield from heapify(arr,i,0) 116 | 117 | def shell_sort(arr): 118 | sublistcount = len(arr) // 2 119 | while sublistcount > 0: 120 | for start_position in range(sublistcount): 121 | yield from gap_InsertionSort(arr, start_position, sublistcount) 122 | sublistcount = sublistcount // 2 123 | 124 | def gap_InsertionSort(nlist,start,gap): 125 | for i in range(start+gap,len(nlist),gap): 126 | 127 | current_value = nlist[i] 128 | position = i 129 | 130 | while position>=gap and nlist[position-gap]>current_value: 131 | nlist[position]=nlist[position-gap] 132 | position = position-gap 133 | yield nlist 134 | 135 | nlist[position]=current_value 136 | yield nlist 137 | 138 | def count_sort(arr): 139 | max_val = max(arr) 140 | m = max_val + 1 141 | count = [0] * m 142 | 143 | for a in arr: 144 | count[a] += 1 145 | yield arr 146 | i = 0 147 | for a in range(m): 148 | for c in range(count[a]): 149 | arr[i] = a 150 | i += 1 151 | yield arr 152 | yield arr 153 | 154 | 155 | 156 | n = int(input("Enter the number of elements:")) 157 | print("\n 1.Bubble \n 2.Insertion \n 3.Quick \n 4.Selection \n 5.Merge Sort \n 6.Heapify \n 7.Shell \n 8.Count sort \n") 158 | al = int(input("Choose algorithm: ")) 159 | array = [i + 1 for i in range(n)] 160 | random.shuffle(array) 161 | 162 | if(al==1): 163 | title = "Bubble Sort" 164 | algo = sort_buble(array) 165 | elif(al==2): 166 | title = "Insertion Sort" 167 | algo = insertion_sort(array) 168 | elif(al==3): 169 | title = "Quick Sort" 170 | algo = quick_Sort(array,0,n-1) 171 | elif(al==4): 172 | title="Selection Sort" 173 | algo = selection_sort(array) 174 | elif (al == 5): 175 | title = "Merge Sort" 176 | algo=merge_sort(array,0,n-1) 177 | elif (al == 6): 178 | title = "Heap Sort" 179 | algo = heap_sort(array) 180 | elif (al == 7): 181 | title = "Shell Sort" 182 | algo = shell_sort(array) 183 | elif (al == 8): 184 | title = "Count Sort" 185 | algo = count_sort(array) 186 | else: 187 | print("Please enter a number from list") 188 | # Initialize fig 189 | fig, ax = plt.subplots() 190 | ax.set_title(title) 191 | 192 | bar_rec = ax.bar(range(len(array)), array, align='edge') 193 | 194 | ax.set_xlim(0, n) 195 | ax.set_ylim(0, int(n * 1.1)) 196 | 197 | text = ax.text(0.02, 0.95, "", transform=ax.transAxes) 198 | 199 | epochs = [0] 200 | 201 | 202 | def update_plot(array, rec, epochs): 203 | for rec, val in zip(rec, array): 204 | rec.set_height(val) 205 | epochs[0]+= 1 206 | text.set_text("No.of operations :{}".format(epochs[0])) 207 | 208 | 209 | anima = anim.FuncAnimation(fig, func=update_plot, fargs=(bar_rec, epochs), frames=algo, interval=1, repeat=False) 210 | plt.show() 211 | --------------------------------------------------------------------------------