├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .idea ├── codeStyles │ └── Project.xml ├── modules.xml ├── sorting-algorithms.iml └── vcs.xml ├── Assembly ├── bubblesort.asm └── quicksort.asm ├── C# ├── BinaryInsertionSort.cs ├── BubbleSort.cs ├── CocktailSort.cs ├── CombSort.cs ├── HeapSort.cs ├── InsertionSort.cs ├── MergeSort.cs ├── QuickSort.cs ├── RadixSort.cs ├── SelectionSort.cs ├── ShellSort.cs └── bucket_sort ├── C++ ├── BinaryInsertionSort.cpp ├── BubbleSort.cpp ├── BubbleSort_withPasses.cpp ├── BucketSort.cpp ├── CocktailSort.cpp ├── CycleSort.cpp ├── Gnome_sort_cpp ├── HeapSort.cpp ├── InsertionSort.cpp ├── InterchangeSort.cpp ├── KWayMergeSort.cpp ├── MergeSort.cpp ├── PigeonholeSort.cpp ├── QuickSort.cpp ├── RadixSort.cpp ├── SelectionSort.cpp ├── ShellSort.cpp ├── cycleSort.cpp └── treeSort.cpp ├── C ├── Bubble-Sort.c ├── BubbleSort.c ├── InsertionSort.c ├── MergeSort.c ├── QuickSort.c ├── SelectionSort.c ├── bucket_sort.c ├── cocktailsort.c ├── gnomesort.c ├── heapsort.c ├── quickSort.c ├── radixsort.c └── treesort.c ├── CODE_OF_CONDUCT.md ├── Elixir └── selectionSort.exs ├── Go ├── BubbleSort.go ├── CountingSort.go ├── InsertionSort.go └── RadixSort.go ├── Java ├── Array_Rotation.java ├── BeadSort.java ├── BinaryInsertionSort.java ├── BitonicSort.java ├── BogoSort.java ├── BubbleSort.java ├── BucketSort.java ├── CocktailSort.java ├── CombSort.java ├── Counting Sort.java ├── CycleSort.java ├── Decagonal_Numbers.java ├── GnomeSort.java ├── HeapSort.java ├── InsertionSort.java ├── MergeSort.java ├── PancakeSort.java ├── PigeonholeSort.java ├── QuickSort.java ├── RadixSort.java ├── SelectionSort.java ├── ShellSort.java ├── TimSort.java ├── TopologicalSort.java └── TreeSort.java ├── Javascript ├── HeapSort.js ├── Insertionsort.js ├── MergeSort.js ├── Quicksort.js ├── RadixSort.js ├── TopologicalSort.js ├── bogoSort.js ├── bubbleSort.js ├── countingSort.js ├── gnomeSort.js ├── selectionSort.js └── shellSort.js ├── Kotlin ├── BogoSort.kt ├── BubbleSort.kt ├── CocktailShakerSort.kt ├── CountingSort.kt ├── HeapSort.kt ├── InsertionSort.kt ├── MergeSort.kt ├── QuickSort.kt ├── RadixSort.kt ├── insertionSort.kt └── selectionSort.kt ├── LICENSE.txt ├── Python ├── BinaryInsertionSort.py ├── BogoSort.py ├── BubbleSort.py ├── BubbleSortRecursive.py ├── BucketSort.py ├── CocktailSort.py ├── CountingSort.py ├── CycleSort.py ├── GnomeSort.py ├── InsertionSort.py ├── MergeSort.py ├── QuickSort.py ├── RadixSort.py ├── SelectionSort.py ├── TimSort.py ├── heapSort.py └── speed_of_sorting_python.PNG ├── README.md ├── Ruby ├── bubble_sort.rb ├── gnome_sort.rb ├── quick_sort.rb ├── reverse.rb ├── selection_sort.rb └── sort.rb ├── Rust └── Bubble_Sort.rs └── lua └── quicksort.lua /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | xmlns:android 14 | 15 | ^$ 16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 | 24 | xmlns:.* 25 | 26 | ^$ 27 | 28 | 29 | BY_NAME 30 | 31 |
32 |
33 | 34 | 35 | 36 | .*:id 37 | 38 | http://schemas.android.com/apk/res/android 39 | 40 | 41 | 42 |
43 |
44 | 45 | 46 | 47 | .*:name 48 | 49 | http://schemas.android.com/apk/res/android 50 | 51 | 52 | 53 |
54 |
55 | 56 | 57 | 58 | name 59 | 60 | ^$ 61 | 62 | 63 | 64 |
65 |
66 | 67 | 68 | 69 | style 70 | 71 | ^$ 72 | 73 | 74 | 75 |
76 |
77 | 78 | 79 | 80 | .* 81 | 82 | ^$ 83 | 84 | 85 | BY_NAME 86 | 87 |
88 |
89 | 90 | 91 | 92 | .* 93 | 94 | http://schemas.android.com/apk/res/android 95 | 96 | 97 | ANDROID_ATTRIBUTE_ORDER 98 | 99 |
100 |
101 | 102 | 103 | 104 | .* 105 | 106 | .* 107 | 108 | 109 | BY_NAME 110 | 111 |
112 |
113 |
114 |
115 |
116 |
-------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/sorting-algorithms.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Assembly/bubblesort.asm: -------------------------------------------------------------------------------- 1 | # bubbleSort.asm 2 | 3 | # SETUP 4 | .data 5 | #set the size and content of array 6 | #Sz: .word 50 7 | Sz: .word 100 8 | Array: 7, 5, 4, 1, 6, 8, 3, 2, 9, 0, 8, 3, 2, 4, 9, 0, 6, 7, 5, 1, 1, 6, 5, 7, 4, 8, 2, 3, 9, 0, 2, 8, 5, 1, 3, 9, 6, 0, 7, 4, 5, 8, 1, 6, 0, 7, 9, 2, 3, 4, 7, 9, 0, 2, 5, 1, 8, 6, 3, 4, 2, 8, 4, 5, 0, 7, 3, 9, 6, 1, 2, 0, 3, 6, 5, 4, 7, 9, 1, 8, 5, 6, 8, 1, 3, 2, 0, 9, 7, 4, 9, 3, 2, 1, 7, 5, 6, 8, 0, 4 9 | 10 | NL: .asciiz "\n" 11 | .text 12 | # Initialize List 13 | main: 14 | lw $s7, Sz # get size of list 15 | move $s1, $zero # set counter for # of elems printed 16 | move $s2, $zero # set offset from Array 17 | 18 | #program in C: 19 | # for (int k = 1; k < size; k++){ 20 | # for (int i = 0; i a[i +1]){ 22 | # int temp = a[i]; 23 | # a[i + 1] = temp; 24 | # } 25 | # } 26 | # } 27 | 28 | #Variable meanings: 29 | #t0; k 30 | #t1: i 31 | #t2: a[i] 32 | #t3: a[i+1] 33 | #t4: size - k 34 | #t5: temp 35 | #s3: [i+1] 36 | 37 | # sort the list: 38 | outer_loop: 39 | beq $t0, $s7, end_of_sort #end loop if counter reached size of array 40 | addi $t1, $zero, 0 #reset inner loop counter 41 | inner_loop: 42 | sub $t4, $s7, $t0 #store the values of size - k for comparison later 43 | beq $t1, $t4, end_of_inner_loop #end inner loop if counter reached comparitor values 44 | mul $s2, $t1, 4 45 | lw $t2, Array($s2) #load a[i] 46 | addi $s3, $s2, 4 47 | lw $t3, Array($s3) #load a[i+1] 48 | 49 | ble $t2, $t3, after_swap 50 | 51 | move $t5, $t2 #store a[i] in temp 52 | move $t2, $t3 #swap 53 | move $t3, $t5 54 | 55 | sw $t2, Array($s2) 56 | sw $t3, Array($s3) 57 | after_swap: 58 | 59 | addi $t1, $t1, 1 #increment inner counter 60 | j inner_loop #jump to start of inner 61 | 62 | end_of_inner_loop: 63 | addi $t0, $t0, 1 #increment outer counter 64 | j outer_loop #jump to start of outer 65 | 66 | end_of_sort: 67 | # main print loop 68 | move $s1, $zero # set counter for # of elems printed 69 | move $s2, $zero # set offset from Array 70 | 71 | print_loop: 72 | bge $s1, $s7, print_loop_end # stop after last elem is printed 73 | lw $a0, Array($s2) # print next value from the list 74 | li $v0, 1 75 | syscall 76 | la $a0, NL # print a newline 77 | li $v0, 4 78 | syscall 79 | addi $s1, $s1, 1 # increment the loop counter 80 | addi $s2, $s2, 4 # step to the next array elem 81 | 82 | j print_loop # repeat the loop 83 | print_loop_end: 84 | -------------------------------------------------------------------------------- /Assembly/quicksort.asm: -------------------------------------------------------------------------------- 1 | #quick sort 2 | 3 | # SETUP 4 | .data 5 | #set the size and content of array 6 | Sz: .word 100 7 | Array: 7, 5, 4, 1, 6, 8, 3, 2, 9, 0, 8, 3, 2, 4, 9, 0, 6, 7, 5, 1, 1, 6, 5, 7, 4, 8, 2, 3, 9, 0, 2, 8, 5, 1, 3, 9, 6, 0, 7, 4, 5, 8, 1, 6, 0, 7, 9, 2, 3, 4, 7, 9, 0, 2, 5, 1, 8, 6, 3, 4, 2, 8, 4, 5, 0, 7, 3, 9, 6, 1, 2, 0, 3, 6, 5, 4, 7, 9, 1, 8, 5, 6, 8, 1, 3, 2, 0, 9, 7, 4, 9, 3, 2, 1, 7, 5, 6, 8, 0, 4 8 | NL: .asciiz "\n" 9 | .text 10 | # Initialize List 11 | main: 12 | lw $s7, Sz # get size of list 13 | move $s1, $zero # set counter for # of elems printed 14 | move $s2, $zero # set offset from Array 15 | j start 16 | quickSort: 17 | #variable list: 18 | #a0: left 19 | #a1: right 20 | #s0: i 21 | #s1: j 22 | #s2: tmp 23 | #s3: pivot 24 | #s4: array access 25 | move $s0, $a0 #i = left 26 | move $s1, $a1 #j = right 27 | add $t0, $a0, $a1 #left + right 28 | div $t0, $t0, 2 #(left + right) / 2 29 | mul $s4, $t0, 4 #array access 30 | lw $s3, Array($s4) #pivot = arr[(left + right) / 2] 31 | outsideWhile: 32 | bgt $s0, $s1, outsideWhileEnd #if i > j escape while 33 | # while (arr[i] < pivot) 34 | # i++; 35 | insideWhile1: 36 | mul $s4, $s0, 4 37 | lw $t0, Array($s4) #arr[i] 38 | bge $t0, $s3, insideWhile1End #escape inside if arr[i] >= pivot 39 | addi $s0, $s0, 1 #i++ 40 | j insideWhile1 41 | insideWhile1End: 42 | # while (arr[j] > pivot) 43 | # j--; 44 | insideWhile2: 45 | mul $s4, $s1, 4 46 | lw $t0, Array($s4) #arr[j] 47 | ble $t0, $s3, insideWhile2End #escape inside if arr[i] >= pivot 48 | subi $s1, $s1, 1 #i++ 49 | j insideWhile2 50 | insideWhile2End: 51 | bgt $s0, $s1, whileIfFalse #if (i <= j) { 52 | mul $s4, $s0, 4 53 | lw $s2, Array($s4) #tmp = arr[i] 54 | 55 | mul $s4, $s1, 4 56 | lw $t0, Array($s4) #access arr[j] 57 | mul $s4, $s0, 4 58 | sw $t0, Array($s4) #arr[i] = arr[j] 59 | 60 | mul $s4, $s1, 4 61 | sw $s2, Array($s4) #arr[j] = tmp; 62 | 63 | addi $s0, $s0, 1 #i++ 64 | subi $s1, $s1, 1 #j-- 65 | whileIfFalse: 66 | j outsideWhile 67 | outsideWhileEnd: 68 | bge $a0, $s1, if1False #if left < j{ 69 | sub $sp, $sp, 12 70 | sw $ra, 8($sp) 71 | sw $a0, 4($sp) 72 | sw $a1, 0($sp) 73 | move $a0, $a0 #left = left 74 | move $a1, $s1 #right = j 75 | jal quickSort 76 | lw $ra, 8($sp) 77 | lw $a0, 4($sp) 78 | lw $a1, 0($sp) 79 | add $sp, $sp, 12 80 | if1False: 81 | 82 | bge $s0, $a1, if2False 83 | sub $sp, $sp, 12 84 | sw $ra, 8($sp) 85 | sw $a0, 4($sp) 86 | sw $a1, 0($sp) 87 | move $a0, $s0 #left = i 88 | move $a1, $a1 #right = right 89 | jal quickSort 90 | lw $ra, 8($sp) 91 | lw $a0, 4($sp) 92 | lw $a1, 0($sp) 93 | add $sp, $sp, 12 94 | if2False: 95 | jr $ra 96 | 97 | start: 98 | addi $a0, $a0, 0 99 | move $a1, $s7 100 | sub $sp, $sp, 12 101 | sw $ra, 8($sp) 102 | sw $a0, 4($sp) 103 | sw $a1, 0($sp) 104 | jal quickSort 105 | lw $ra, 8($sp) 106 | lw $a0, 4($sp) 107 | lw $a1, 0($sp) 108 | add $sp, $sp, 12 109 | 110 | # main print loop 111 | move $s1, $zero 112 | move $s2, $zero 113 | print_loop: 114 | bge $s1, $s7, print_loop_end # stop after last elem is printed 115 | lw $a0, Array($s2) # print next value from the list 116 | li $v0, 1 117 | syscall 118 | la $a0, NL # print a newline 119 | li $v0, 4 120 | syscall 121 | addi $s1, $s1, 1 # increment the loop counter 122 | addi $s2, $s2, 4 # step to the next array elem 123 | 124 | j print_loop # repeat the loop 125 | print_loop_end: 126 | -------------------------------------------------------------------------------- /C#/BinaryInsertionSort.cs: -------------------------------------------------------------------------------- 1 | // C# Program implementing 2 | // binary insertion sort 3 | using System; 4 | 5 | class GFG { 6 | 7 | public static void Main() 8 | { 9 | int []arr = {37, 23, 0, 17, 12, 72, 31, 10 | 46, 100, 88, 54 }; 11 | 12 | sort(arr); 13 | 14 | for(int i = 0; i < arr.Length; i++) 15 | Console.Write(arr[i] + " "); 16 | } 17 | 18 | public static void sort(int []array) 19 | { 20 | for (int i = 1; i < array.Length; i++) 21 | { 22 | int x = array[i]; 23 | 24 | // Find location to insert using 25 | // binary search 26 | int j = Math.Abs(Array.BinarySearch( 27 | array, 0, i, x) + 1); 28 | 29 | // Shifting array to one location right 30 | System.Array.Copy(array, j, array, 31 | j+1, i-j); 32 | 33 | // Placing element at its correct 34 | // location 35 | array[j] = x; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /C#/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | // Bubble Sort with C# 2 | using System; 3 | 4 | namespace BubbleSort 5 | { 6 | class MainClass 7 | { 8 | public static void Main() 9 | { 10 | // test numbers to sort 11 | int[] toSort = { 5, 2, 6, 8, 3}; 12 | 13 | // perform bubble sort 14 | for (int i = 0; i < 5; i++) 15 | { 16 | for (int j = 0; j < 4; j++) 17 | { 18 | if (toSort[j] > toSort[j + 1]) 19 | { 20 | int temp = toSort[j]; 21 | toSort[j] = toSort[j + 1]; 22 | toSort[j + 1] = temp; 23 | } 24 | } 25 | } 26 | 27 | // print to console results 28 | for (int i = 0; i < 5; i++) 29 | { 30 | Console.WriteLine(toSort[i]); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /C#/CocktailSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class GFG { 4 | 5 | static void cocktailSort(int[] a) 6 | { 7 | bool swapped = true; 8 | int start = 0; 9 | int end = a.Length; 10 | 11 | while (swapped == true) { 12 | 13 | // reset the swapped flag on entering the 14 | // loop, because it might be true from a 15 | // previous iteration. 16 | swapped = false; 17 | 18 | // loop from bottom to top same as 19 | // the bubble sort 20 | for (int i = start; i < end - 1; ++i) { 21 | if (a[i] > a[i + 1]) { 22 | int temp = a[i]; 23 | a[i] = a[i + 1]; 24 | a[i + 1] = temp; 25 | swapped = true; 26 | } 27 | } 28 | 29 | // if nothing moved, then array is sorted. 30 | if (swapped == false) 31 | break; 32 | 33 | // otherwise, reset the swapped flag so that it 34 | // can be used in the next stage 35 | swapped = false; 36 | 37 | // move the end point back by one, because 38 | // item at the end is in its rightful spot 39 | end = end - 1; 40 | 41 | // from top to bottom, doing the 42 | // same comparison as in the previous stage 43 | for (int i = end - 1; i >= start; i--) { 44 | if (a[i] > a[i + 1]) { 45 | int temp = a[i]; 46 | a[i] = a[i + 1]; 47 | a[i + 1] = temp; 48 | swapped = true; 49 | } 50 | } 51 | 52 | // increase the starting point, because 53 | // the last stage would have moved the next 54 | // smallest number to its rightful spot. 55 | start = start + 1; 56 | } 57 | } 58 | 59 | /* Prints the array */ 60 | static void printArray(int[] a) 61 | { 62 | int n = a.Length; 63 | for (int i = 0; i < n; i++) 64 | Console.Write(a[i] + " "); 65 | Console.WriteLine(); 66 | } 67 | 68 | // Driver method 69 | public static void Main() 70 | { 71 | int[] a = { 5, 1, 4, 2, 8, 0, 2 }; 72 | cocktailSort(a); 73 | Console.WriteLine("Sorted array "); 74 | printArray(a); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /C#/CombSort.cs: -------------------------------------------------------------------------------- 1 | // C# program for implementation of Comb Sort 2 | using System; 3 | 4 | class Combsort 5 | { 6 | // To find gap between elements 7 | static int getNextGap(int gap) 8 | { 9 | // Shrink gap by Shrink factor 10 | gap = (gap*10)/13; 11 | if (gap < 1) 12 | return 1; 13 | return gap; 14 | } 15 | 16 | // Function to sort arr[] using Comb Sort 17 | static void sort(int []arr) 18 | { 19 | int n = arr.Length; 20 | 21 | // initialize gap 22 | int gap = n; 23 | 24 | // Initialize swapped as true to 25 | // make sure that loop runs 26 | bool swapped = true; 27 | 28 | // Keep running while gap is more than 29 | // 1 and last iteration caused a swap 30 | while (gap != 1 || swapped == true) 31 | { 32 | // Find next gap 33 | gap = getNextGap(gap); 34 | 35 | // Initialize swapped as false so that we can 36 | // check if swap happened or not 37 | swapped = false; 38 | 39 | // Compare all elements with current gap 40 | for (int i=0; i arr[i+gap]) 43 | { 44 | // Swap arr[i] and arr[i+gap] 45 | int temp = arr[i]; 46 | arr[i] = arr[i+gap]; 47 | arr[i+gap] = temp; 48 | 49 | // Set swapped 50 | swapped = true; 51 | } 52 | } 53 | } 54 | } 55 | public static void Main() 56 | { 57 | int []arr = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 58 | sort(arr); 59 | 60 | Console.WriteLine("sorted array"); 61 | for (int i=0; i= 0; i--) 9 | { 10 | adjust(i, 9); 11 | } 12 | for (i = 8; i >= 0; i--) 13 | { 14 | t = r[i + 1]; 15 | r[i + 1] = r[0]; 16 | r[0] = t; 17 | adjust(0, i); 18 | } 19 | } 20 | private void adjust(int i, int n) 21 | { 22 | int t, j; 23 | try 24 | { 25 | t = r[i]; 26 | j = 2 * i; 27 | while (j <= n) 28 | { 29 | if (j < n && r[j] < r[j + 1]) 30 | j++; 31 | if (t >=r[j]) 32 | break; 33 | r[j / 2] = r[j]; 34 | j *= 2; 35 | } 36 | r[j / 2] = t; 37 | } 38 | catch (IndexOutOfRangeException e) 39 | { 40 | Console.WriteLine("Array Out of Bounds ", e); 41 | } 42 | } 43 | public void print() 44 | { 45 | for (int i = 0; i < 10; i++) 46 | { 47 | Console.WriteLine("{0}", r[i]); 48 | } 49 | 50 | } 51 | public static void Main() 52 | { 53 | heap obj = new heap(); 54 | Console.WriteLine("Elements Before sorting : "); 55 | obj.print(); 56 | obj.hsort(); 57 | Console.WriteLine("Elements After sorting : "); 58 | obj.print(); 59 | Console.Read(); 60 | } 61 | } -------------------------------------------------------------------------------- /C#/InsertionSort.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * C# Program to Perform Insertion Sort 3 | */ 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.IO; 9 | namespace ConsoleApplication1 10 | { 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | int[] arr = new int[5] { 83, 12, 3, 34, 60 }; 16 | int i; 17 | Console.WriteLine("The Array is :"); 18 | for (i = 0; i < 5; i++) 19 | { 20 | Console.WriteLine(arr[i]); 21 | } 22 | insertsort(arr, 5); 23 | Console.WriteLine("The Sorted Array is :"); 24 | for (i = 0; i < 5; i++) 25 | Console.WriteLine(arr[i]); 26 | Console.ReadLine(); 27 | } 28 | static void insertsort(int[] data, int n) 29 | { 30 | int i, j; 31 | for (i = 1; i < n; i++) 32 | { 33 | int item = data[i]; 34 | int ins = 0; 35 | for (j = i - 1; j >= 0 && ins != 1; ) 36 | { 37 | if (item < data[j]) 38 | { 39 | data[j + 1] = data[j]; 40 | j--; 41 | data[j + 1] = item; 42 | } 43 | else ins = 1; 44 | } 45 | } 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /C#/MergeSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace CSharpMergeSort 6 | { 7 | class Mergesort 8 | { 9 | 10 | static public void DoMerge(int [] numbers, int left, int mid, int right) 11 | { 12 | int [] temp = new int[25]; 13 | int i, left_end, num_elements, tmp_pos; 14 | 15 | left_end = (mid - 1); 16 | tmp_pos = left; 17 | num_elements = (right - left + 1); 18 | 19 | while ((left <= left_end) && (mid <= right)) 20 | { 21 | if (numbers[left] <= numbers[mid]) 22 | temp[tmp_pos++] = numbers[left++]; 23 | else 24 | temp[tmp_pos++] = numbers[mid++]; 25 | } 26 | 27 | while (left <= left_end) 28 | temp[tmp_pos++] = numbers[left++]; 29 | 30 | while (mid <= right) 31 | temp[tmp_pos++] = numbers[mid++]; 32 | 33 | for (i = 0; i < num_elements; i++) 34 | { 35 | numbers[right] = temp[right]; 36 | right--; 37 | } 38 | } 39 | 40 | static public void MergeSort_Recursive(int [] numbers, int left, int right) 41 | { 42 | int mid; 43 | 44 | if (right > left) 45 | { 46 | mid = (right + left) / 2; 47 | MergeSort_Recursive(numbers, left, mid); 48 | MergeSort_Recursive(numbers, (mid + 1), right); 49 | 50 | DoMerge(numbers, left, (mid+1), right); 51 | } 52 | } 53 | 54 | static void Main(string[] args) 55 | { 56 | int[] numbers = { 3, 8, 7, 5, 2, 1, 9, 6, 4 }; 57 | int len = 9; 58 | 59 | Console.WriteLine("MergeSort By Recursive Method"); 60 | MergeSort_Recursive(numbers, 0, len - 1); 61 | for (int i = 0; i < 9; i++) 62 | Console.WriteLine(numbers[i]); 63 | 64 | Console.WriteLine(numbers[i]); 65 | 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /C#/QuickSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace sortQuickAlgorithm 7 | { 8 | class quickSortAlgorithm 9 | { 10 | 11 | private int[] array = new int[20]; 12 | private int len; 13 | 14 | public void QuickSortAlgorithm() 15 | { 16 | sort(0, len - 1); 17 | } 18 | 19 | public void sort(int left, int right) 20 | { 21 | int pivot, leftend, rightend; 22 | 23 | leftend = left; 24 | rightend = right; 25 | pivot = array[left]; 26 | 27 | while (left < right) { while ((array[right] >= pivot) && (left < right)) 28 | { 29 | right--; 30 | } 31 | 32 | if (left != right) 33 | { 34 | array[left] = array[right]; 35 | left++; 36 | } 37 | 38 | while ((array[left] >= pivot) && (left < right)) 39 | { 40 | left++; 41 | } 42 | 43 | if (left != right) 44 | { 45 | array[right] = array[left]; 46 | right--; 47 | } 48 | } 49 | 50 | array[left] = pivot; 51 | pivot = left; 52 | left = leftend; 53 | right = rightend; 54 | 55 | if (left < pivot) { sort(left, pivot - 1); } if (right > pivot) 56 | { 57 | sort(pivot + 1, right); 58 | } 59 | } 60 | 61 | public static void Main() 62 | { 63 | quickSortAlgorithm q_Sort = new quickSortAlgorithm(); 64 | 65 | int[] array = { 41, 32, 15, 45, 63, 72, 57, 43, 32, 52, 183}; 66 | q_Sort.array = array; 67 | q_Sort.len = q_Sort.array.Length; 68 | q_Sort.QuickSortAlgorithm(); 69 | 70 | for (int j = 0; j < q_Sort.len; j++) 71 | { 72 | Console.WriteLine(q_Sort.array[j]); 73 | } 74 | Console.ReadKey(); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /C#/RadixSort.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * C# Program to Perform Radix Sort 3 | */ 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace ConsoleApplication2 10 | { 11 | class Example 12 | { 13 | private int[] data; 14 | private IList> digits = new List>(); 15 | private int maxLength = 0; 16 | public Example() 17 | { 18 | for (int i = 0; i < 10; i++) 19 | { 20 | digits.Add(new List()); 21 | } 22 | Console.Write("Enter the Number of Records : "); 23 | int count = int.Parse(Console.ReadLine()); 24 | data = new int[count]; 25 | Console.ReadLine(); 26 | for (int i = 0; i < count; i++) 27 | { 28 | Console.Write("Enter Record {0} : ", i + 1); 29 | 30 | data[i] = int.Parse(Console.ReadLine()); 31 | 32 | if (maxLength < data[i].ToString().Length) 33 | maxLength = data[i].ToString().Length; 34 | } 35 | } 36 | 37 | public void RadixSort() 38 | { 39 | for (int i = 0; i < maxLength; i++) 40 | { 41 | for (int j = 0; j < data.Length; j++) 42 | { 43 | int digit = (int)((data[j] % Math.Pow(10, i + 1)) / Math.Pow(10, i)); 44 | 45 | digits[digit].Add(data[j]); 46 | } 47 | 48 | int index = 0; 49 | for (int k = 0; k < digits.Count; k++) 50 | { 51 | IList selDigit = digits[k]; 52 | 53 | for (int l = 0; l < selDigit.Count; l++) 54 | { 55 | data[index++] = selDigit[l]; 56 | } 57 | } 58 | ClearDigits(); 59 | } 60 | printSortedData(); 61 | } 62 | 63 | private void ClearDigits() 64 | { 65 | for (int k = 0; k < digits.Count; k++) 66 | { 67 | digits[k].Clear(); 68 | } 69 | } 70 | 71 | public void printSortedData() 72 | { 73 | Console.WriteLine("The Sorted Numbers are : "); 74 | for (int i = 0; i < data.Length; i++) 75 | { 76 | Console.WriteLine(data[i]); 77 | } 78 | } 79 | static void Main(string[] args) 80 | { 81 | new Example().RadixSort(); 82 | 83 | Console.ReadLine(); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /C#/SelectionSort.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * C# Program to Perform a Selection Sort 3 | */ 4 | using System; 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | int array_size = 10; 10 | int[] array = new int[10] { 100, 50, 20, 40, 10, 60, 80, 70, 90, 30 }; 11 | Console.WriteLine("The Array Before Selection Sort is: "); 12 | for (int i = 0; i < array_size; i++) 13 | { 14 | Console.WriteLine(array[i]); 15 | } 16 | int tmp, min_key; 17 | 18 | for (int j = 0; j < array_size - 1; j++) 19 | { 20 | min_key = j; 21 | 22 | for (int k = j + 1; k < array_size; k++) 23 | { 24 | if (array[k] < array[min_key]) 25 | { 26 | min_key = k; 27 | } 28 | } 29 | 30 | tmp = array[min_key]; 31 | array[min_key] = array[j]; 32 | array[j] = tmp; 33 | } 34 | 35 | Console.WriteLine("The Array After Selection Sort is: "); 36 | for (int i = 0; i < 10; i++) 37 | { 38 | Console.WriteLine(array[i]); 39 | } 40 | Console.ReadLine(); 41 | } 42 | } -------------------------------------------------------------------------------- /C#/ShellSort.cs: -------------------------------------------------------------------------------- 1 | private void SortArrayWithShellSort() 2 | { 3 | int[] array = { 297,183, 464 }; 4 | ShellSort(array); 5 | } 6 | 7 | 8 | private void ShellSort(int[] array) 9 | { 10 | int n = array.Length; 11 | int gap = n / 2; 12 | int temp; 13 | 14 | while (gap > 0) 15 | { 16 | for (int i = 0; i + gap < n; i++) 17 | { 18 | int j = i + gap; 19 | temp = array[j]; 20 | 21 | while (j - gap >= 0 && temp < array[j - gap]) 22 | { 23 | array[j] = array[j - gap]; 24 | j = j - gap; 25 | } 26 | 27 | array[j] = temp; 28 | } 29 | 30 | gap = gap / 2; 31 | } 32 | } -------------------------------------------------------------------------------- /C#/bucket_sort: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Sorting_Algorithms_In_C_Sharp 8 | { 9 | public static class BucketSort 10 | { 11 | //Bucket sort breaks a list down into sub-lists, you can then use another algo to sort the sub-lists 12 | //Bucketsort isn't a good choice if you don't know the range or distribution of the data 13 | //Bucket Sort time complexity 14 | //Average case: O(n+k) - k being the number of buckets that were created 15 | //Worst case: O(N^2) 16 | 17 | //In this case, we will focus on building an algorithm that uses bucketsort to sort an array of integers between 1 and 99 18 | //we will also assume that the integers in the passed array are evenly distributed 19 | public static List BucketSort1(params int[] x) 20 | { 21 | List result = new List(); 22 | 23 | //Determine how many buckets you want to create, in this case, the 10 buckets will each contain a range of 10 24 | //1-10, 11-20, 21-30, etc. since the passed array is between 1 and 99 25 | int numOfBuckets = 10; 26 | 27 | //Create buckets 28 | List[] buckets = new List[numOfBuckets]; 29 | for (int i = 0; i < numOfBuckets; i++) 30 | buckets[i] = new List(); 31 | 32 | //Iterate through the passed array and add each integer to the appropriate bucket 33 | for (int i = 0; i < x.Length; i++) 34 | { 35 | int buckitChoice = (x[i] / numOfBuckets); 36 | buckets[buckitChoice].Add(x[i]); 37 | } 38 | 39 | //Sort each bucket and add it to the result List 40 | //Each sublist is sorted using Bubblesort, but you could substitute any sorting algo you would like 41 | for (int i = 0; i < numOfBuckets; i++) 42 | { 43 | int [] temp = BubbleSortList(buckets[i]); 44 | result.AddRange(temp); 45 | } 46 | return result; 47 | } 48 | 49 | //Bubblesort w/ ListInput 50 | public static int[] BubbleSortList(List input) 51 | { 52 | for (int i = 0; i < input.Count; i++) 53 | { 54 | for (int j = 0; j < input.Count; j++) 55 | { 56 | if (input[i] < input[j]) 57 | { 58 | int temp = input[i]; 59 | input[i] = input[j]; 60 | input[j] = temp; 61 | } 62 | } 63 | } 64 | return input.ToArray(); 65 | } 66 | ////Call in Program.cs to test 67 | //int[] x = new int[] { 99, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 1 }; 68 | //List sorted = Bucket_Sort.BucketSort(x); 69 | //foreach (int i in sorted) 70 | // Console.WriteLine(i); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /C++/BinaryInsertionSort.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C program for implementation of binary insertion sort 3 | #include 4 | 5 | // A binary search based function to find the position 6 | // where item should be inserted in a[low..high] 7 | int binarySearch(int a[], int item, int low, int high) 8 | { 9 | if (high <= low) 10 | return (item > a[low])? (low + 1): low; 11 | 12 | int mid = (low + high)/2; 13 | 14 | if(item == a[mid]) 15 | return mid+1; 16 | 17 | if(item > a[mid]) 18 | return binarySearch(a, item, mid+1, high); 19 | return binarySearch(a, item, low, mid-1); 20 | } 21 | 22 | // Function to sort an array a[] of size 'n' 23 | void insertionSort(int a[], int n) 24 | { 25 | int i, loc, j, k, selected; 26 | 27 | for (i = 1; i < n; ++i) 28 | { 29 | j = i - 1; 30 | selected = a[i]; 31 | 32 | // find location where selected sould be inseretd 33 | loc = binarySearch(a, selected, 0, j); 34 | 35 | // Move all elements after location to create space 36 | while (j >= loc) 37 | { 38 | a[j+1] = a[j]; 39 | j--; 40 | } 41 | a[j+1] = selected; 42 | } 43 | } 44 | 45 | // Driver program to test above function 46 | int main() 47 | { 48 | int a[] = {37, 23, 0, 17, 12, 72, 31, 49 | 46, 100, 88, 54}; 50 | int n = sizeof(a)/sizeof(a[0]), i; 51 | 52 | insertionSort(a, n); 53 | 54 | printf("Sorted array: \n"); 55 | for (i = 0; i < n; i++) 56 | printf("%d ",a[i]); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /C++/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void BubbleSort(int arr[], int n){ 5 | int minIndex, temp; 6 | for(int i = 0 ; i>n; 28 | int arr[n]; 29 | 30 | for(int i =0; i>arr[i]; 32 | } 33 | 34 | BubbleSort(arr,(sizeof(arr)/sizeof(arr[0]))); 35 | 36 | for( int i = 0 ;i 3 | using namespace std; 4 | 5 | int arr[10]; 6 | int n, i; 7 | 8 | void bubble_sort(int arr[], int n); 9 | void display(int arr[], int n); 10 | void passes(int arr[], int n); 11 | 12 | int main() 13 | { 14 | cout<<"\n------BUBBLE SORT------"; 15 | cout<<"\n\nEnter no. of Array elements: "; 16 | cin>>n; 17 | cout<<"\nEnter Array elements: "; 18 | for(i=0; i>arr[i]; 21 | } 22 | cout<<"\nUnsorted Array: ["; 23 | for(i=0; iarr[j+1]) 42 | { 43 | temp=arr[j]; 44 | arr[j]=arr[j+1]; 45 | arr[j+1]=temp; 46 | passes(arr, n); 47 | } 48 | 49 | } 50 | } 51 | 52 | } 53 | 54 | void display(int arr[], int n) 55 | { 56 | cout<<"\n\nSorted Array: ["; 57 | for(i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | void display(float *array, int size) { 6 | for(int i = 0; i bucket[size]; 12 | for(int i = 0; i> n; 30 | float arr[n]; //create an array with given number of elements 31 | cout << "Enter elements:" << endl; 32 | for(int i = 0; i> arr[i]; 34 | } 35 | cout << "Array before Sorting: "; 36 | display(arr, n); 37 | bucketSort(arr, n); 38 | cout << "Array after Sorting: "; 39 | display(arr, n); 40 | } 41 | -------------------------------------------------------------------------------- /C++/CocktailSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Sorts arrar a[0..n-1] using Cocktail sort 5 | void CocktailSort(int a[], int n) 6 | { 7 | bool swapped = true; 8 | int start = 0; 9 | int end = n - 1; 10 | 11 | while (swapped) { 12 | // reset the swapped flag on entering 13 | // the loop, because it might be true from 14 | // a previous iteration. 15 | swapped = false; 16 | 17 | // loop from left to right same as 18 | // the bubble sort 19 | for (int i = start; i < end; ++i) { 20 | if (a[i] > a[i + 1]) { 21 | swap(a[i], a[i + 1]); 22 | swapped = true; 23 | } 24 | } 25 | 26 | // if nothing moved, then array is sorted. 27 | if (!swapped) 28 | break; 29 | 30 | // otherwise, reset the swapped flag so that it 31 | // can be used in the next stage 32 | swapped = false; 33 | 34 | // move the end point back by one, because 35 | // item at the end is in its rightful spot 36 | --end; 37 | 38 | // from right to left, doing the 39 | // same comparison as in the previous stage 40 | for (int i = end - 1; i >= start; --i) { 41 | if (a[i] > a[i + 1]) { 42 | swap(a[i], a[i + 1]); 43 | swapped = true; 44 | } 45 | } 46 | 47 | // increase the starting point, because 48 | // the last stage would have moved the next 49 | // smallest number to its rightful spot. 50 | ++start; 51 | } 52 | } 53 | 54 | /* Prints the array */ 55 | void printArray(int a[], int n) 56 | { 57 | for (int i = 0; i < n; i++) 58 | printf("%d ", a[i]); 59 | printf("\n"); 60 | } 61 | 62 | // Driver code 63 | int main() 64 | { 65 | int arr[] = { 5, 1, 4, 2, 8, 0, 2 }; 66 | int n = sizeof(arr) / sizeof(arr[0]); 67 | CocktailSort(a, n); 68 | printf("Sorted array :\n"); 69 | printArray(a, n); 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /C++/CycleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void cycleSort(int arr[], int n) 4 | { 5 | int writes = 0; 6 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { 7 | int item = arr[cycle_start]; 8 | int pos = cycle_start; 9 | for (int i = cycle_start + 1; i < n; i++) 10 | if (arr[i] < item) 11 | pos++; 12 | if (pos == cycle_start) 13 | continue; 14 | while (item == arr[pos]) 15 | pos += 1; 16 | if (pos != cycle_start) { 17 | swap(item, arr[pos]); 18 | writes++; 19 | } 20 | while (pos != cycle_start) { 21 | pos = cycle_start; 22 | for (int i = cycle_start + 1; i < n; i++) 23 | if (arr[i] < item) 24 | pos += 1; 25 | while (item == arr[pos]) 26 | pos += 1; 27 | if (item != arr[pos]) { 28 | swap(item, arr[pos]); 29 | writes++; 30 | } 31 | } 32 | } 33 | } 34 | 35 | int main() 36 | { 37 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | cycleSort(arr, n); 40 | 41 | cout << "After sort : " << endl; 42 | for (int i = 0; i < n; i++) 43 | cout << arr[i] << " "; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /C++/Gnome_sort_cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A function to sort the algorithm using gnome sort 5 | void gnomeSort(int arr[], int n) 6 | { 7 | int index = 0; 8 | 9 | while (index < n) { 10 | if (index == 0) 11 | index++; 12 | if (arr[index] >= arr[index - 1]) 13 | index++; 14 | else { 15 | swap(arr[index], arr[index - 1]); 16 | index--; 17 | } 18 | } 19 | return; 20 | } 21 | 22 | // A utility function ot print an array of size n 23 | void printArray(int arr[], int n) 24 | { 25 | cout << "Sorted sequence after Gnome sort: "; 26 | for (int i = 0; i < n; i++) 27 | cout << arr[i] << " "; 28 | cout << "\n"; 29 | } 30 | 31 | // Driver program to test above functions. 32 | int main() 33 | { 34 | int arr[] = { 34, 2, 10, -9 }; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | 37 | gnomeSort(arr, n); 38 | printArray(arr, n); 39 | 40 | return (0); 41 | } 42 | -------------------------------------------------------------------------------- /C++/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | //Heap Sort 2 | //Author: Ravi Prakash (https://github.com/ravi-prakash1907) 3 | 4 | #include 5 | #include 6 | 7 | int comparison = 0; 8 | 9 | void display(int *a, int size) { 10 | cout<<"{ "; 11 | for(int i=0; i a[largest]){ 29 | largest = left; 30 | comparison+=2; 31 | } 32 | if(right < heapSize && a[right] > a[largest]){ 33 | largest = right; 34 | comparison+=2; 35 | } 36 | 37 | if(largest != index){ 38 | comparison++; 39 | swap(a, largest, index); 40 | maxHeapify(a, largest, heapSize); 41 | } 42 | } 43 | 44 | void buildMaxHeap(int *a, int n) 45 | { 46 | for (int i = (n/2) - 1; i >= 0; i--) { 47 | maxHeapify(a, i, n); 48 | comparison++; 49 | } 50 | } 51 | 52 | void heapSort(int *a, int size) 53 | { 54 | buildMaxHeap(a, size); 55 | int heapSize = size, i; 56 | for(i=size-1; i>=0; i--) { 57 | swap(a, 0, i); 58 | heapSize--; 59 | comparison++; 60 | maxHeapify(a,0,heapSize); 61 | } 62 | } 63 | 64 | void main() 65 | { 66 | clrscr(); 67 | int size, i, *arr; 68 | cout<<"\nEnter the size of array (max. 10): "; 69 | cin>>size; 70 | arr = new int[size]; 71 | 72 | cout<<"\nEnter the array: \n"; 73 | for(i=0; i>arr[i]; 75 | clrscr(); 76 | 77 | cout<<"\n Your array: \n"; 78 | display(arr, size); 79 | getch(); 80 | clrscr(); 81 | 82 | heapSort(arr, size); 83 | cout<<"\n\nTotal comperision made: "< 2 | using namespace std; 3 | void display(int *array, int n) { 4 | for(int i = 0; i 0 && array[j-1]>key) { 14 | array[j] = array[j-1]; 15 | j--; 16 | } 17 | array[j] = key; //insert in right place 18 | } 19 | } 20 | int main() { 21 | int n; 22 | cout << "Enter the number of elements: "; 23 | cin >> n; 24 | int arr[n]; //create an array with given number of elements 25 | cout << "Enter elements:" << endl; 26 | for(int i = 0; i> arr[i]; 28 | } 29 | cout << "Array before Sorting: "; 30 | display(arr, n); 31 | insertionSort(arr, n); 32 | cout << "Array after Sorting: "; 33 | display(arr, n); 34 | } -------------------------------------------------------------------------------- /C++/InterchangeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void swap(int &a, int &b) 7 | { 8 | int x = a; 9 | a = b; 10 | b = x; 11 | } 12 | 13 | void interchange_sort(int a[], int n) 14 | { 15 | for (int i = 0; i < n-1;i++) 16 | for (int j = i + 1; j < n;j++) 17 | if (a[i]>a[j]) 18 | swap(a[i], a[j]); 19 | } 20 | 21 | int main() 22 | { 23 | int n =10; 24 | int a[] = {8, 6, 3, 7, 1, 8, 2, 8, 1, 11}; 25 | interchange_sort(a, n); 26 | for(int i = 0; i < n; i++) 27 | { 28 | cout << a[i] << " "; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /C++/KWayMergeSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to merge k sorted arrays of size n each. 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | #define n 4 7 | 8 | // A min heap node 9 | struct MinHeapNode 10 | { 11 | int element; // The element to be stored 12 | int i; // index of the array from which the element is taken 13 | int j; // index of the next element to be picked from array 14 | }; 15 | 16 | // Prototype of a utility function to swap two min heap nodes 17 | void swap(MinHeapNode *x, MinHeapNode *y); 18 | 19 | // A class for Min Heap 20 | class MinHeap 21 | { 22 | MinHeapNode *harr; // pointer to array of elements in heap 23 | int heap_size; // size of min heap 24 | public: 25 | // Constructor: creates a min heap of given size 26 | MinHeap(MinHeapNode a[], int size); 27 | 28 | // to heapify a subtree with root at given index 29 | void MinHeapify(int ); 30 | 31 | // to get index of left child of node at index i 32 | int left(int i) { return (2*i + 1); } 33 | 34 | // to get index of right child of node at index i 35 | int right(int i) { return (2*i + 2); } 36 | 37 | // to get the root 38 | MinHeapNode getMin() { return harr[0]; } 39 | 40 | // to replace root with new node x and heapify() new root 41 | void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); } 42 | }; 43 | 44 | // This function takes an array of arrays as an argument and 45 | // All arrays are assumed to be sorted. It merges them together 46 | // and prints the final sorted output. 47 | int *mergeKArrays(int arr[][n], int k) 48 | { 49 | int *output = new int[n*k]; // To store output array 50 | 51 | // Create a min heap with k heap nodes. Every heap node 52 | // has first element of an array 53 | MinHeapNode *harr = new MinHeapNode[k]; 54 | for (int i = 0; i < k; i++) 55 | { 56 | harr[i].element = arr[i][0]; // Store the first element 57 | harr[i].i = i; // index of array 58 | harr[i].j = 1; // Index of next element to be stored from array 59 | } 60 | MinHeap hp(harr, k); // Create the heap 61 | 62 | // Now one by one get the minimum element from min 63 | // heap and replace it with next element of its array 64 | for (int count = 0; count < n*k; count++) 65 | { 66 | // Get the minimum element and store it in output 67 | MinHeapNode root = hp.getMin(); 68 | output[count] = root.element; 69 | 70 | // Find the next elelement that will replace current 71 | // root of heap. The next element belongs to same 72 | // array as the current root. 73 | if (root.j < n) 74 | { 75 | root.element = arr[root.i][root.j]; 76 | root.j += 1; 77 | } 78 | // If root was the last element of its array 79 | else root.element = INT_MAX; //INT_MAX is for infinite 80 | 81 | // Replace root with next element of array 82 | hp.replaceMin(root); 83 | } 84 | 85 | return output; 86 | } 87 | 88 | // FOLLOWING ARE IMPLEMENTATIONS OF STANDARD MIN HEAP METHODS 89 | // FROM CORMEN BOOK 90 | // Constructor: Builds a heap from a given array a[] of given size 91 | MinHeap::MinHeap(MinHeapNode a[], int size) 92 | { 93 | heap_size = size; 94 | harr = a; // store address of array 95 | int i = (heap_size - 1)/2; 96 | while (i >= 0) 97 | { 98 | MinHeapify(i); 99 | i--; 100 | } 101 | } 102 | 103 | // A recursive method to heapify a subtree with root at given index 104 | // This method assumes that the subtrees are already heapified 105 | void MinHeap::MinHeapify(int i) 106 | { 107 | int l = left(i); 108 | int r = right(i); 109 | int smallest = i; 110 | if (l < heap_size && harr[l].element < harr[i].element) 111 | smallest = l; 112 | if (r < heap_size && harr[r].element < harr[smallest].element) 113 | smallest = r; 114 | if (smallest != i) 115 | { 116 | swap(&harr[i], &harr[smallest]); 117 | MinHeapify(smallest); 118 | } 119 | } 120 | 121 | // A utility function to swap two elements 122 | void swap(MinHeapNode *x, MinHeapNode *y) 123 | { 124 | MinHeapNode temp = *x; *x = *y; *y = temp; 125 | } 126 | 127 | // A utility function to print array elements 128 | void printArray(int arr[], int size) 129 | { 130 | for (int i=0; i < size; i++) 131 | cout << arr[i] << " "; 132 | } 133 | 134 | // Driver program to test above functions 135 | int main() 136 | { 137 | // Change n at the top to change number of elements 138 | // in an array 139 | int arr[][n] = {{2, 6, 12, 34}, 140 | {1, 9, 20, 1000}, 141 | {23, 34, 90, 2000}}; 142 | int k = sizeof(arr)/sizeof(arr[0]); 143 | 144 | int *output = mergeKArrays(arr, k); 145 | 146 | cout << "Merged array is " << endl; 147 | printArray(output, n*k); 148 | 149 | return 0; 150 | } -------------------------------------------------------------------------------- /C++/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | //Merge Sort 2 | //Author: Ravi Prakash (https://github.com/ravi-prakash1907) 3 | 4 | #include 5 | #include 6 | 7 | template 8 | void swap(T *one, T *two) 9 | { 10 | T temp = *one; 11 | *one = *two; 12 | *two = temp; 13 | } 14 | 15 | //--------------------------------------// 16 | 17 | void merge(int arr[], int l, int m, int r) 18 | { 19 | int i, j, k; 20 | int n1 = m - l + 1; 21 | int n2 = r - m; 22 | 23 | int L[n1], R[n2]; 24 | 25 | for (i = 0; i < n1; i++) 26 | L[i] = arr[l + i]; 27 | for (j = 0; j < n2; j++) 28 | R[j] = arr[m + 1+ j]; 29 | 30 | //------ 31 | 32 | i = j = 0; 33 | k = l; 34 | while (i < n1 && j < n2) 35 | { arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++]; } 36 | while (i < n1) 37 | { arr[k++] = L[i++]; } 38 | while (j < n2) 39 | { arr[k++] = R[j++]; } 40 | } 41 | 42 | /* SORTING */ 43 | void mergeSort(int arr[], int l, int r) 44 | { 45 | if (l < r) 46 | { 47 | int m = l+(r-l)/2; 48 | 49 | mergeSort(arr, l, m); 50 | mergeSort(arr, m+1, r); 51 | 52 | merge(arr, l, m, r); 53 | } 54 | } 55 | 56 | //--------------------------------------// 57 | 58 | template 59 | void getArr(T arr[], int n) 60 | { 61 | cout<<"Enter the array: "; 62 | for(int i=0; i>arr[i]; 64 | } 65 | 66 | template 67 | void putArr(T arr[], int n) 68 | { 69 | cout<<"Sorted array: \n\n"; 70 | for(int i=0; i 76 | void main() 77 | { 78 | clrscr(); 79 | T arr[6], x; 80 | int size; 81 | 82 | cout<<"Enter size of the array: "; 83 | cin>>size; 84 | 85 | getArr(arr, size); 86 | 87 | mergeSort(arr, 0, size-1); 88 | 89 | putArr(arr, size); 90 | 91 | getch(); 92 | } -------------------------------------------------------------------------------- /C++/PigeonholeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void pigeonhole_sort(int arr[],int n) 6 | { 7 | int minm=arr[0],maxm=arr[0]; 8 | for(int i=1;imaxm) 13 | maxm=arr[i]; 14 | } 15 | int range=maxm-minm+1; 16 | vectorholes[range]; 17 | for(int i=0;i>n; 32 | int arr[n]; 33 | cout<<"Enter elements of the array : "; 34 | for(int i=0;i>arr[i]; 36 | pigeonhole_sort(arr,n); 37 | cout<<"Sorted array is : "< 5 | #include 6 | 7 | template 8 | void swap(T *one, T *two) 9 | { 10 | T temp = *one; 11 | *one = *two; 12 | *two = temp; 13 | } 14 | 15 | //--------------------------------------// 16 | 17 | int partition (int arr[], int low, int high) 18 | { 19 | int pivot = arr[high]; 20 | int i = (low - 1); 21 | 22 | for (int j = low; j <= high- 1; j++) 23 | { 24 | if (arr[j] <= pivot) 25 | { 26 | i++; 27 | swap(&arr[i], &arr[j]); 28 | } 29 | } 30 | swap(&arr[i + 1], &arr[high]); 31 | return (i + 1); 32 | } 33 | 34 | void quickSort(int arr[], int low, int high) 35 | { 36 | if (low < high) 37 | { 38 | int pi = partition(arr, low, high); 39 | 40 | quickSort(arr, low, pi - 1); 41 | quickSort(arr, pi + 1, high); 42 | } 43 | } 44 | 45 | //--------------------------------------// 46 | 47 | template 48 | void getArr(T arr[], int n) 49 | { 50 | cout<<"Enter the array: "; 51 | for(int i=0; i>arr[i]; 53 | } 54 | 55 | template 56 | void putArr(T arr[], int n) 57 | { 58 | cout<<"Sorted array: \n\n"; 59 | for(int i=0; i 65 | void main() 66 | { 67 | clrscr(); 68 | T arr[6], x; 69 | int size; 70 | 71 | cout<<"Enter size of the array: "; 72 | cin>>size; 73 | 74 | getArr(arr, size); 75 | 76 | quickSort(arr, 0, size-1); 77 | 78 | putArr(arr, size); 79 | 80 | getch(); 81 | } -------------------------------------------------------------------------------- /C++/RadixSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A utility function to get maximum value in arr[] 5 | int getMax(int arr[], int n) 6 | { 7 | int mx = arr[0]; 8 | for (int i = 1; i < n; i++) 9 | if (arr[i] > mx) 10 | mx = arr[i]; 11 | return mx; 12 | } 13 | 14 | // A function to do counting sort of arr[] according to 15 | // the digit represented by exp. 16 | void countSort(int arr[], int n, int exp) 17 | { 18 | int output[n]; // output array 19 | int i, count[10] = {0}; 20 | 21 | // Store count of occurrences in count[] 22 | for (i = 0; i < n; i++) 23 | count[ (arr[i]/exp)%10 ]++; 24 | 25 | // Change count[i] so that count[i] now contains actual 26 | // position of this digit in output[] 27 | for (i = 1; i < 10; i++) 28 | count[i] += count[i - 1]; 29 | 30 | // Build the output array 31 | for (i = n - 1; i >= 0; i--) 32 | { 33 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 34 | count[ (arr[i]/exp)%10 ]--; 35 | } 36 | 37 | // Copy the output array to arr[], so that arr[] now 38 | // contains sorted numbers according to current digit 39 | for (i = 0; i < n; i++) 40 | arr[i] = output[i]; 41 | } 42 | 43 | // The main function to that sorts arr[] of size n using 44 | // Radix Sort 45 | void radixsort(int arr[], int n) 46 | { 47 | // Find the maximum number to know number of digits 48 | int m = getMax(arr, n); 49 | 50 | // Do counting sort for every digit. Note that instead 51 | // of passing digit number, exp is passed. exp is 10^i 52 | // where i is current digit number 53 | for (int exp = 1; m/exp > 0; exp *= 10) 54 | countSort(arr, n, exp); 55 | } 56 | 57 | // A utility function to print an array 58 | void print(int arr[], int n) 59 | { 60 | for (int i = 0; i < n; i++) 61 | cout << arr[i] << " "; 62 | } 63 | 64 | // Driver program to test above functions 65 | int main() 66 | { 67 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 68 | int n = sizeof(arr)/sizeof(arr[0]); 69 | radixsort(arr, n); 70 | print(arr, n); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /C++/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { //swap the content of a and b 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int n) { 10 | for(int i = 0; i> n; 29 | int arr[n]; //create an array with given number of elements 30 | cout << "Enter elements:" << endl; 31 | for(int i = 0; i> arr[i]; 33 | } 34 | 35 | selectionSort(arr, n); 36 | cout << "Array after Sorting: "; 37 | display(arr, n); 38 | } -------------------------------------------------------------------------------- /C++/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | //Shell Sort 2 | //Author: Ravi Prakash (https://github.com/ravi-prakash1907) 3 | 4 | #include 5 | #include 6 | 7 | template 8 | void swap(T *one, T *two) 9 | { 10 | T temp = *one; 11 | *one = *two; 12 | *two = temp; 13 | } 14 | 15 | //--------------------------------------// 16 | 17 | template 18 | void shellSort(T arr[], int n) 19 | { 20 | for (int gap = n/2; gap > 0; gap /= 2) 21 | { 22 | for (int i = gap; i < n; i += 1) 23 | { 24 | int temp = arr[i]; 25 | 26 | int j; 27 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 28 | arr[j] = arr[j - gap]; 29 | 30 | arr[j] = temp; 31 | } 32 | } 33 | } 34 | 35 | //--------------------------------------// 36 | 37 | template 38 | void getArr(T arr[], int n) 39 | { 40 | cout<<"Enter the array: "; 41 | for(int i=0; i>arr[i]; 43 | } 44 | 45 | template 46 | void putArr(T arr[], int n) 47 | { 48 | cout<<"Sorted array: \n\n"; 49 | for(int i=0; i 55 | void main() 56 | { 57 | clrscr(); 58 | T arr[6], x; 59 | int size; 60 | 61 | cout<<"Enter size of the array: "; 62 | cin>>size; 63 | 64 | getArr(arr, size); 65 | 66 | shellSort(arr, size); 67 | 68 | putArr(arr, size); 69 | 70 | getch(); 71 | } -------------------------------------------------------------------------------- /C++/cycleSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement cycle sort 2 | #include 3 | using namespace std; 4 | 5 | // Function sort the array using Cycle sort 6 | void cycleSort(int arr[], int n) 7 | { 8 | // count number of memory writes 9 | int writes = 0; 10 | 11 | // traverse array elements and put it to on 12 | // the right place 13 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { 14 | // initialize item as starting point 15 | int item = arr[cycle_start]; 16 | 17 | // Find position where we put the item. We basically 18 | // count all smaller elements on right side of item. 19 | int pos = cycle_start; 20 | for (int i = cycle_start + 1; i < n; i++) 21 | if (arr[i] < item) 22 | pos++; 23 | 24 | // If item is already in correct position 25 | if (pos == cycle_start) 26 | continue; 27 | 28 | // ignore all duplicate elements 29 | while (item == arr[pos]) 30 | pos += 1; 31 | 32 | // put the item to it's right position 33 | if (pos != cycle_start) { 34 | swap(item, arr[pos]); 35 | writes++; 36 | } 37 | 38 | // Rotate rest of the cycle 39 | while (pos != cycle_start) { 40 | pos = cycle_start; 41 | 42 | // Find position where we put the element 43 | for (int i = cycle_start + 1; i < n; i++) 44 | if (arr[i] < item) 45 | pos += 1; 46 | 47 | // ignore all duplicate elements 48 | while (item == arr[pos]) 49 | pos += 1; 50 | 51 | // put the item to it's right position 52 | if (item != arr[pos]) { 53 | swap(item, arr[pos]); 54 | writes++; 55 | } 56 | } 57 | } 58 | 59 | // Number of memory writes or swaps 60 | // cout << writes << endl ; 61 | } 62 | 63 | // Driver program to test above function 64 | int main() 65 | { 66 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 67 | int n = sizeof(arr) / sizeof(arr[0]); 68 | cycleSort(arr, n); 69 | 70 | cout << "After sort : " << endl; 71 | for (int i = 0; i < n; i++) 72 | cout << arr[i] << " "; 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /C++/treeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int key; 7 | struct Node *left, *right; 8 | }; 9 | 10 | struct Node *newNode(int item) 11 | { 12 | struct Node *temp = new Node; 13 | temp->key = item; 14 | temp->left = temp->right = NULL; 15 | return temp; 16 | } 17 | 18 | void storeSorted(Node *root, int arr[], int &i) 19 | { 20 | if (root != NULL) 21 | { 22 | storeSorted(root->left, arr, i); 23 | arr[i++] = root->key; 24 | storeSorted(root->right, arr, i); 25 | } 26 | } 27 | 28 | /* A utility function to insert a new 29 | Node with given key in BST */ 30 | 31 | Node* insert(Node* node, int key) 32 | { 33 | /* If the tree is empty, return a new Node */ 34 | 35 | if (node == NULL) return newNode(key); 36 | 37 | /* Otherwise, recur down the tree */ 38 | 39 | if (key < node->key) 40 | node->left = insert(node->left, key); 41 | else if (key > node->key) 42 | node->right = insert(node->right, key); 43 | 44 | /* return the (unchanged) Node pointer */ 45 | 46 | return node; 47 | } 48 | 49 | // This function sorts arr[0..n-1] using Tree Sort 50 | 51 | void treeSort(int arr[], int n) 52 | { 53 | struct Node *root = NULL; 54 | 55 | root = insert(root, arr[0]); 56 | for (int i=1; i 2 | #include 3 | void main() 4 | { 5 | int n,i,j; 6 | char name[50][50],temp[50]; 7 | printf("Enter how many names:\t"); 8 | scanf("%d",&n); 9 | printf("Enter the names\n"); 10 | for(i=0;i0) 21 | { 22 | strcpy(temp,name[j]); 23 | strcpy(name[j],name[j+1]); 24 | strcpy(name[j+1],temp); 25 | } 26 | } 27 | } 28 | printf("The names in order\n"); 29 | for(i=0;i 2 | #include 3 | 4 | int main(void){ 5 | int nums[] = {5,1,4,2,8}; 6 | for (int outer = 0; outer < 4; outer++) 7 | { 8 | int didSwap = 0; 9 | for (int inner = outer; inner < 4; inner++) 10 | { 11 | if(nums[inner] > nums[inner+1]) 12 | { 13 | int temp = nums[inner]; 14 | nums[inner] = nums[inner+1]; 15 | nums[inner+1] = temp; 16 | didSwap = 1; 17 | } 18 | 19 | } 20 | 21 | } 22 | for (int i = 0; i<5; i++) 23 | { 24 | printf("%i\n", nums[i]); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /C/InsertionSort.c: -------------------------------------------------------------------------------- 1 | # include 2 | int main(void) 3 | { 4 | int ar[10], key, i, j; 5 | printf ("Enter 10 numbers: \n"); 6 | for (i=0; i<10; i++) 7 | scanf ("%d", &ar[i]); 8 | for (i=1; i<10; i++) 9 | { 10 | key = ar[i]; 11 | j = i-1; 12 | while (j>=0 && ar[j]>key) 13 | { 14 | ar[j+1] = ar[j]; 15 | j = j-1; 16 | } 17 | ar[j+1] = key; 18 | } 19 | printf ("The Sorted array:\n"); 20 | for (i=0; i<10; i++) 21 | printf ("ar[%d] = %d\n", i, ar[i]); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /C/MergeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void merge(int arr[], int l, int m, int r) 3 | { 4 | int i, j, k; 5 | int n1 = m - l + 1; 6 | int n2 = r - m; 7 | int L[n1], R[n2]; 8 | for (i = 0; i < n1; i++) 9 | L[i] = arr[l + i]; 10 | for (j = 0; j < n2; j++) 11 | R[j] = arr[m + 1+ j]; 12 | i = 0; 13 | j = 0; 14 | k = l; 15 | while (i < n1 && j < n2) 16 | { 17 | if (L[i] <= R[j]) 18 | { 19 | arr[k] = L[i]; 20 | i++; 21 | } 22 | else 23 | { 24 | arr[k] = R[j]; 25 | j++; 26 | } 27 | k++; 28 | } 29 | while (i < n1) 30 | { 31 | arr[k] = L[i]; 32 | i++; 33 | k++; 34 | } 35 | while (j < n2) 36 | { 37 | arr[k] = R[j]; 38 | j++; 39 | k++; 40 | } 41 | } 42 | void mergeSort(int arr[], int l, int r) 43 | { 44 | if (l < r) 45 | { 46 | int m = l+(r-l)/2; 47 | mergeSort(arr, l, m); 48 | mergeSort(arr, m+1, r); 49 | merge(arr, l, m, r); 50 | } 51 | } 52 | void printArray(int A[], int size) 53 | { 54 | int i; 55 | for (i=0; i < size; i++) 56 | printf("%d ", A[i]); 57 | printf("\n"); 58 | } 59 | int main() 60 | { 61 | int arr[] = {12, 11, 13, 5, 6, 7}; 62 | int arr_size = sizeof(arr)/sizeof(arr[0]); 63 | 64 | printf("Given array is \n"); 65 | printArray(arr, arr_size); 66 | 67 | mergeSort(arr, 0, arr_size - 1); 68 | 69 | printf("\nSorted array is \n"); 70 | printArray(arr, arr_size); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /C/QuickSort.c: -------------------------------------------------------------------------------- 1 | void quickSort(int *vetor, int inicio, int fim){ 2 | int i = inicio, f = fim, pivot = vetor[(inicio + fim) / 2], aux; 3 | do { 4 | while(vetor[i] < pivot) 5 | i++; 6 | while(vetor[f] > pivot) 7 | f--; 8 | if(i <= f){ 9 | aux = vetor[i]; 10 | vetor[i++] = vetor[f]; 11 | vetor[f--] = aux; 12 | } 13 | } while(i < f); 14 | if(inicio < f) 15 | quickSort(vetor, inicio, f); 16 | if(i < fim) 17 | quickSort(vetor, i, fim); 18 | } 19 | -------------------------------------------------------------------------------- /C/SelectionSort.c: -------------------------------------------------------------------------------- 1 | # include 2 | #define MAX 1000 3 | int main(void) 4 | { 5 | int i, j, N, pos, temp; 6 | int ar[MAX]; 7 | printf ("Enter the number of integers to sort:"); 8 | scanf ("%d", &N); 9 | printf ("Enter the integers: \n"); 10 | for (i=0; i 3 | int getMax(int array[], int size) 4 | { 5 | int max = array[0]; 6 | for (int i = 1; i < size; i++) 7 | if (array[i] > max) 8 | max = array[i]; 9 | return max; 10 | } 11 | void bucketSort(int array[], int size) 12 | { 13 | // The size of bucket must be at least the (max+1) but 14 | // we cannot assign declare it as int bucket(max+1) in C as 15 | // it does not support dynamic memory allocation. 16 | // So, its size is provided statically. 17 | int bucket[10]; 18 | const int max = getMax(array, size); 19 | for (int i = 0; i <= max; i++) 20 | { 21 | bucket[i] = 0; 22 | } 23 | for (int i = 0; i < size; i++) 24 | { 25 | bucket[array[i]]++; 26 | } 27 | for (int i = 0, j = 0; i <= max; i++) 28 | { 29 | while (bucket[i] > 0) 30 | { 31 | array[j++] = i; 32 | bucket[i]--; 33 | } 34 | } 35 | } 36 | void printArray(int array[], int size) 37 | { 38 | for (int i = 0; i < size; ++i) 39 | { 40 | printf("%d ", array[i]); 41 | } 42 | printf("\n"); 43 | } 44 | int main() 45 | { 46 | int data[] = {4, 3, 4, 5, 6, 0, 9, 5}; 47 | int size = sizeof(data) / sizeof(data[0]); 48 | bucketSort(data, size); 49 | printf("Sorted array in ascending order: \n"); 50 | printArray(data, size); 51 | } 52 | -------------------------------------------------------------------------------- /C/cocktailsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int* a, int* b) { 4 | *a = *a + *b; 5 | *b = *a - *b; 6 | *a = *a - *b; 7 | } 8 | 9 | void cocktailsort(int array[], int n) { 10 | int swap_status = 1; 11 | int start = 0, end = n - 1; 12 | 13 | while(swap_status == 1) { 14 | swap_status = 0; 15 | 16 | for(int i = start; i < end; i++) { 17 | if(array[i] > array[i+1]) { 18 | swap(&array[i], &array[i+1]); 19 | swap_status = 1; 20 | } 21 | } 22 | 23 | if(swap_status == 0) { 24 | break; 25 | } 26 | 27 | swap_status = 0; 28 | 29 | end -= 1; 30 | 31 | for(int i = end - 1; i >= start; i--) { 32 | if(array[i] > array[i+1]) { 33 | swap(&array[i], &array[i+1]); 34 | swap_status = 1; 35 | } 36 | } 37 | 38 | start += 1; 39 | } 40 | } 41 | 42 | void Display(int array[], int n) { 43 | for(int i = 0; i < n; i++) { 44 | printf("%d ", array[i]); 45 | } 46 | printf("\n"); 47 | } 48 | 49 | int main() { 50 | int arr[] = {1, 5, 3, 7, 3, 7, 2, 5, 3, 56, 46}; 51 | int n = sizeof(arr) / sizeof(arr[0]); 52 | Display(arr, n); 53 | cocktailsort(arr, n); 54 | Display(arr, n); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /C/gnomesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAX 6 4 | 5 | int main(){ 6 | int TableToAnalyse[MAX]={1,2,-4,3,9,6}; 7 | int mygnomeindex=1; 8 | printf("size %d\n",MAX); 9 | 10 | while (mygnomeindex!=MAX-1){ 11 | if(TableToAnalyse[mygnomeindex]>=TableToAnalyse[mygnomeindex-1]){ 12 | mygnomeindex++; 13 | }else{ 14 | int c=TableToAnalyse[mygnomeindex]; 15 | TableToAnalyse[mygnomeindex]=TableToAnalyse[mygnomeindex-1]; 16 | TableToAnalyse[mygnomeindex-1]=c; 17 | mygnomeindex--; 18 | } 19 | } 20 | printf("Resultat:\n"); 21 | printf("%d",TableToAnalyse[0]); 22 | for (int i=1;i 5 | 6 | void main() 7 | { 8 | int heap[10], no, i, j, c, root, temp; 9 | 10 | printf("\n Enter no of elements :"); 11 | scanf("%d", &no); 12 | printf("\n Enter the nos : "); 13 | for (i = 0; i < no; i++) 14 | scanf("%d", &heap[i]); 15 | for (i = 1; i < no; i++) 16 | { 17 | c = i; 18 | do 19 | { 20 | root = (c - 1) / 2; 21 | if (heap[root] < heap[c]) /* to create MAX heap array */ 22 | { 23 | temp = heap[root]; 24 | heap[root] = heap[c]; 25 | heap[c] = temp; 26 | } 27 | c = root; 28 | } while (c != 0); 29 | } 30 | 31 | printf("Heap array : "); 32 | for (i = 0; i < no; i++) 33 | printf("%d\t ", heap[i]); 34 | for (j = no - 1; j >= 0; j--) 35 | { 36 | temp = heap[0]; 37 | heap[0] = heap[j /* swap max element with rightmost leaf element */ 38 | heap[j] = temp; 39 | root = 0; 40 | do 41 | { 42 | c = 2 * root + 1; /* left node of root element */ 43 | if ((heap[c] < heap[c + 1]) && c < j-1) 44 | c++; 45 | if (heap[root] pivot) 7 | f--; 8 | if(i <= f){ 9 | aux = vetor[i]; 10 | vetor[i++] = vetor[f]; 11 | vetor[f--] = aux; 12 | } 13 | } while(i < f); 14 | if(inicio < f) 15 | quickSort(vetor, inicio, f); 16 | if(i < fim) 17 | quickSort(vetor, i, fim); 18 | } -------------------------------------------------------------------------------- /C/radixsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int getMax(int arr[], int n) 6 | { 7 | int mx = arr[0]; 8 | for (int i = 1; i < n; i++) 9 | if (arr[i] > mx) 10 | mx = arr[i]; 11 | return mx; 12 | } 13 | 14 | void countSort(int arr[], int n, int exp) 15 | { 16 | int output[n]; // output array 17 | int i, count[10] = {0}; 18 | 19 | for (i = 0; i < n; i++) 20 | count[ (arr[i]/exp)%10 ]++; 21 | for (i = 1; i < 10; i++) 22 | count[i] += count[i - 1]; 23 | for (i = n - 1; i >= 0; i--) 24 | { 25 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 26 | count[ (arr[i]/exp)%10 ]--; 27 | } 28 | for (i = 0; i < n; i++) 29 | arr[i] = output[i]; 30 | } 31 | 32 | void radixsort(int arr[], int n) 33 | { 34 | int m = getMax(arr, n); 35 | for (int exp = 1; m/exp > 0; exp *= 10) 36 | countSort(arr, n, exp); 37 | } 38 | 39 | void print(int arr[], int n) 40 | { 41 | for (int i = 0; i < n; i++) 42 | cout << arr[i] << " "; 43 | } 44 | 45 | int main() 46 | { 47 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 48 | int n = sizeof(arr)/sizeof(arr[0]); 49 | radixsort(arr, n); 50 | printf(arr, n); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C/treesort.c: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int key; 7 | struct Node *left, *right; 8 | }; 9 | 10 | struct Node *newNode(int item) 11 | { 12 | struct Node *temp = new Node; 13 | temp->key = item; 14 | temp->left = temp->right = NULL; 15 | return temp; 16 | } 17 | 18 | void storeSorted(Node *root, int arr[], int &i) 19 | { 20 | if (root != NULL) 21 | { 22 | storeSorted(root->left, arr, i); 23 | arr[i++] = root->key; 24 | storeSorted(root->right, arr, i); 25 | } 26 | } 27 | 28 | Node* insert(Node* node, int key) 29 | { 30 | if (node == NULL) return newNode(key); 31 | 32 | if (key < node->key) 33 | node->left = insert(node->left, key); 34 | else if (key > node->key) 35 | node->right = insert(node->right, key); 36 | 37 | return node; 38 | } 39 | 40 | void treeSort(int arr[], int n) 41 | { 42 | struct Node *root = NULL; 43 | 44 | root = insert(root, arr[0]); 45 | for (int i=1; i 0; i-- { 8 | //The inner loop will first iterate through the full length 9 | //the next iteration will be through n-1 10 | // the next will be through n-2 and so on 11 | for j := 1; j < i; j++ { 12 | if numbers[j-1] > numbers[j] { 13 | intermediate := numbers[j] 14 | numbers[j] = numbers[j-1] 15 | numbers[j-1] = intermediate 16 | } 17 | } 18 | } 19 | return numbers 20 | } 21 | func main() { 22 | a := []int{2, 212, 3001, 14, 501, 7800, 9932, 33, 45, 45, 45, 91, 99, 37, 102, 102, 104, 106, 109, 106} 23 | fmt.Println(BubbleSort(a)) 24 | } 25 | -------------------------------------------------------------------------------- /Go/CountingSort.go: -------------------------------------------------------------------------------- 1 | package main 2 | import "fmt" 3 | 4 | const MaxUint = ^uint(0) 5 | const MaxInt = int(MaxUint >> 1) 6 | const MinInt = - MaxInt - 1 7 | 8 | func countingSort(list []int) { 9 | maxNumber := MinInt 10 | minNumber := MaxInt 11 | for _, v := range list { 12 | if v > maxNumber { 13 | maxNumber = v 14 | } 15 | if v < minNumber { 16 | minNumber = v 17 | } 18 | } 19 | 20 | count := make([]int, maxNumber - minNumber + 1) 21 | 22 | for _, x := range list { 23 | count[x - minNumber]++ 24 | } 25 | index := 0 26 | for i, c := range count { 27 | for ; c > 0; c-- { 28 | list[index] = i + minNumber 29 | index++ 30 | } 31 | } 32 | } 33 | 34 | func main() { 35 | var x int 36 | fmt.Printf("Enter the size of the array : ") 37 | fmt.Scan(&x) 38 | fmt.Printf("Enter the elements of the array : ") 39 | a := make([]int, x) 40 | for i := 0; i < x; i++ { 41 | fmt.Scan(&a[i]) 42 | } 43 | list := a // A copy of the array 'a' is assigned to 'list' 44 | fmt.Println("before sorting", list) 45 | countingSort(list) 46 | fmt.Println("after sorting", list) 47 | } 48 | 49 | /* 50 | Sample Input : 51 | Enter the size of the array : 4 52 | Enter the elements of the array : 12 29 10 78 53 | Sample Output : 54 | After sorting [10 12 29 78] 55 | */ 56 | -------------------------------------------------------------------------------- /Go/InsertionSort.go: -------------------------------------------------------------------------------- 1 | import ("fmt") 2 | 3 | func insertionsort(items []int) { 4 |     var n = len(items) 5 |     for i := 1; i < n; i++ { 6 |         j := i 7 |         for j > 0 { 8 |             if items[j-1] > items[j] { 9 |                 items[j-1], items[j] = items[j], items[j-1] 10 |             } 11 |             j = j - 1 12 |         } 13 |     } 14 | } 15 | 16 | func main() { 17 | unsorted :=[]int{9386, 234, 369, 4863, 611, 1, 0, 55, 69, 928, 2267, 28} 18 | fmt.Println("Unsorted:", unsorted, "\n") 19 | 20 | sorted := radixSort(unsorted) 21 | fmt.Println("\nSorted:", sorted, "\n") 22 | } 23 | -------------------------------------------------------------------------------- /Go/RadixSort.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "fmt" 3 | "strconv" 4 | ) 5 | 6 | func largest(arr []int) int { 7 | max := 0 8 | 9 | for i := 0; i < len(arr); i++ { 10 | if arr[i] > max { 11 | max = arr[i] 12 | } 13 | } 14 | return max 15 | } 16 | 17 | func radixSort(arr []int) []int { 18 | 19 | // base 10 20 | max := largest(arr) 21 | size := len(arr) 22 | significantDigit := 1 23 | partial := make([]int, size, size) 24 | 25 | for max / significantDigit > 0 { 26 | 27 | bucket := [10]int{0} 28 | 29 | for i := 0; i < size; i++ { 30 | bucket[(arr[i] / significantDigit) % 10]++ 31 | } 32 | 33 | for i := 1; i < 10; i++ { 34 | bucket[i] += bucket[i - 1] 35 | } 36 | 37 | for i := size - 1; i >= 0; i-- { 38 | bucket[(arr[i] / significantDigit) % 10]-- 39 | partial[bucket[(arr[i] / significantDigit) % 10]] = arr[i] 40 | } 41 | 42 | for i := 0; i < size; i++ { 43 | arr[i] = partial[i] 44 | } 45 | 46 | significantDigit *= 10 47 | } 48 | 49 | return arr 50 | } 51 | 52 | func main() { 53 | 54 | unsorted :=[]int{9386, 234, 369, 4863, 611, 1, 0, 55, 69, 928, 2267, 28} 55 | fmt.Println("Unsorted:", unsorted, "\n") 56 | 57 | sorted := radixSort(unsorted) 58 | fmt.Println("\nSorted:", sorted, "\n") 59 | } -------------------------------------------------------------------------------- /Java/Array_Rotation.java: -------------------------------------------------------------------------------- 1 | //Program to rotate array Arr[] of size n by d Elements to either left or right 2 | import java.util.Scanner; 3 | class Array_Rotation 4 | { 5 | private static void leftRotate(int arr[], int n) 6 | { 7 | int temp = arr[0], i; 8 | // shifting all the elements of the array to left 9 | for (i = 0; i < n - 1; i++) 10 | arr[i] = arr[i + 1]; 11 | 12 | arr[i] = temp; 13 | } 14 | 15 | private static void rightRotate(int arr[], int n) 16 | { 17 | int temp = arr[n-1], i; 18 | // shifting all the elements of the array to right 19 | for (i = n-1; i > 0; i--) 20 | arr[i] = arr[i - 1]; 21 | 22 | arr[0] = temp; 23 | } 24 | private static void RotateArrayLeft(int arr[], int rotations, int n) 25 | { 26 | // call for rotation one by one 27 | for (int i = 0; i < rotations; i++) 28 | leftRotate(arr, n); 29 | 30 | // print the array 31 | for (int i = 0; i < n; i++) 32 | System.out.print(arr[i] + " "); 33 | } 34 | private static void RotateArrayRight(int arr[], int rotations, int n) 35 | { 36 | // call for rotation one by one 37 | for (int i = 0; i < rotations; i++) 38 | rightRotate(arr, n); 39 | 40 | // print the array 41 | for (int i = 0; i < n; i++) 42 | System.out.print(arr[i] + " "); 43 | } 44 | 45 | public static void main(String args[]) 46 | { 47 | // Sample input 48 | Scanner sc = new Scanner(System.in); 49 | System.out.println("Enter number of elements in array"); 50 | int n=sc.nextInt(); 51 | System.out.println("Enter "+ n +" elements"); 52 | //declare an array that has n elements in it 53 | int a[] = new int[n]; 54 | for(int i = 0; i < n; i++) 55 | a[i] = sc.nextInt(); 56 | System.out.println("Enter number of rotations"); 57 | int d = sc.nextInt(); 58 | System.out.println("To rotate left press 1,\nTo rotate right press 2"); 59 | int choice = sc.nextInt(); 60 | 61 | switch(choice) 62 | { 63 | case 1: 64 | { 65 | RotateArrayLeft(a, d, n); 66 | break; 67 | } 68 | case 2: 69 | { 70 | RotateArrayRight(a, d, n); 71 | break; 72 | } 73 | default: 74 | { 75 | System.out.println("Enter correct choice(1 / 2"); 76 | break; 77 | } 78 | } 79 | 80 | } 81 | } 82 | /* 83 | INPUT 84 | Enter number of elements in array 85 | 5 86 | Enter 5 elements 87 | 1 88 | 2 89 | 3 90 | 4 91 | 5 92 | Enter number of rotations 93 | 2 94 | To rotate left press 1, 95 | To rotate right press 2 96 | 1 97 | OUTPUT 98 | 3 4 5 1 2 99 | */ 100 | -------------------------------------------------------------------------------- /Java/BeadSort.java: -------------------------------------------------------------------------------- 1 | public class BeadSort { 2 | public static void main(String[] args) { 3 | BeadSort now=new BeadSort(); 4 | 5 | int[] arr = new int[(int)(Math.random() * 11) + 5]; 6 | for(int i = 0;i < arr.length; i++) 7 | arr[i] = (int)(Math.random() * 10); 8 | 9 | System.out.print("Unsorted: "); 10 | now.display1D(arr); 11 | 12 | int[] sort = now.beadSort(arr); 13 | System.out.print("Sorted: "); 14 | now.display1D(sort); 15 | } 16 | 17 | int[] beadSort(int[] arr) { 18 | int max = arr[0]; 19 | 20 | for(int i = 1; i < arr.length; i++) 21 | if(arr[i] > max) 22 | max = arr[i]; 23 | 24 | char[][] grid = new char[arr.length][max]; 25 | int[] levelcount = new int[max]; 26 | for(int i = 0; i < max; i++) { 27 | levelcount[i] = 0; 28 | for(int j = 0; j < arr.length; j++) 29 | grid[j][i] = '_'; 30 | } 31 | 32 | for(int i = 0; i < arr.length; i++) { 33 | int num = arr[i]; 34 | for(int j = 0; num > 0; j++) { 35 | grid[levelcount[j]++][j] = '*'; 36 | num--; 37 | } 38 | } 39 | System.out.println(); 40 | display2D(grid); 41 | 42 | int[] sorted = new int[arr.length]; 43 | for(int i = 0; i < arr.length; i++) { 44 | int putt = 0; 45 | for(int j = 0; j < max && grid[arr.length-1-i][j] == '*'; j++) 46 | putt++; 47 | sorted[i] = putt; 48 | } 49 | 50 | return sorted; 51 | } 52 | 53 | void display1D(int[] arr) { 54 | for(int i = 0; i < arr.length; i++) 55 | System.out.print(arr[i] + " "); 56 | System.out.println(); 57 | } 58 | 59 | void display1D(char[] arr) { 60 | for(int i = 0; i < arr.length; i++) 61 | System.out.print(arr[i] + " "); 62 | System.out.println(); 63 | } 64 | 65 | void display2D(char[][] arr) { 66 | for(int i = 0; i < arr.length; i++) 67 | display1D(arr[i]); 68 | System.out.println(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Java/BinaryInsertionSort.java: -------------------------------------------------------------------------------- 1 | // Java Program implementing 2 | // binary insertion sort 3 | 4 | import java.util.Arrays; 5 | class GFG 6 | { 7 | public static void main(String[] args) 8 | { 9 | final int[] arr = {37, 23, 0, 17, 12, 72, 31, 10 | 46, 100, 88, 54 }; 11 | 12 | new GFG().sort(arr); 13 | 14 | for(int i=0; i a[j]) agrees 7 | with the direction, then a[i] and a[j] are 8 | interchanged. */ 9 | void compAndSwap(int a[], int i, int j, int dir) 10 | { 11 | if ( (a[i] > a[j] && dir == 1) || 12 | (a[i] < a[j] && dir == 0)) 13 | { 14 | // Swapping elements 15 | int temp = a[i]; 16 | a[i] = a[j]; 17 | a[j] = temp; 18 | } 19 | } 20 | 21 | /* It recursively sorts a bitonic sequence in ascending 22 | order, if dir = 1, and in descending order otherwise 23 | (means dir=0). The sequence to be sorted starts at 24 | index position low, the parameter cnt is the number 25 | of elements to be sorted.*/ 26 | void bitonicMerge(int a[], int low, int cnt, int dir) 27 | { 28 | if (cnt>1) 29 | { 30 | int k = cnt/2; 31 | for (int i=low; i1) 45 | { 46 | int k = cnt/2; 47 | 48 | // sort in ascending order since dir here is 1 49 | bitonicSort(a, low, k, 1); 50 | 51 | // sort in descending order since dir here is 0 52 | bitonicSort(a,low+k, k, 0); 53 | 54 | // Will merge wole sequence in ascending order 55 | // since dir=1. 56 | bitonicMerge(a, low, cnt, dir); 57 | } 58 | } 59 | 60 | /*Caller of bitonicSort for sorting the entire array 61 | of length N in ASCENDING order */ 62 | void sort(int a[], int N, int up) 63 | { 64 | bitonicSort(a, 0, N, up); 65 | } 66 | 67 | /* A utility function to print array of size n */ 68 | static void printArray(int arr[]) 69 | { 70 | int n = arr.length; 71 | for (int i=0; i 30 | * Bogo-Sort is one of the dumbest ways to sort an array. 31 | * It is full random and shouldn't be used at all! 32 | * It's so inefficient that there isn't any lower bounds in O-notation. 33 | * (It's just random, right?) 34 | *

35 | * The algorithm swaps two indices in the array... until the array is sorted. 36 | *

37 | * More information: https://en.wikipedia.org/wiki/Bogosort 38 | * 39 | * @param array unsorted array of integer 40 | */ 41 | public static void sort(int[] array) { 42 | Random random = ThreadLocalRandom.current(); 43 | 44 | while (!isSorted(array)) { 45 | // Create some random indices 46 | int indexA = random.nextInt(array.length); 47 | int indexB = random.nextInt(array.length); 48 | 49 | // Swap index a with b 50 | int temp = array[indexA]; 51 | array[indexA] = array[indexB]; 52 | array[indexB] = temp; 53 | } 54 | } 55 | 56 | /** 57 | * Check if an array is sorted. 58 | * An array is sorted if it's empty or: 59 | * a[i] <= a[i + 1] for every i in 0..a.length - 1 60 | * 61 | * @param array array 62 | * @return true if the array is sorted, otherwise false 63 | */ 64 | private static boolean isSorted(int[] array) { 65 | if (array.length == 0 || array.length == 1) { 66 | return true; 67 | } 68 | 69 | for (int i = 0; i < array.length - 1; i++) { 70 | if (array[i] > array[i + 1]) { 71 | return false; 72 | } 73 | } 74 | 75 | return true; 76 | } 77 | } -------------------------------------------------------------------------------- /Java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | 2 | public class BubbleSort { 3 | //verifies if the arry is already sorted 4 | //Thus, the best time complexity is improved from O(n^2) to O(n) 5 | static void improvedBubbleSort(int[] arr) { 6 | 7 | int n = arr.length; 8 | int temp = 0; 9 | 10 | boolean flag = true; 11 | 12 | for (int i = 0; i < n && flag; i++) { 13 | 14 | flag = false; 15 | for (int j = 1; j < (n - i); j++) { 16 | 17 | if (arr[j - 1] > arr[j]) { 18 | 19 | temp = arr[j - 1]; 20 | arr[j - 1] = arr[j]; 21 | arr[j] = temp; 22 | 23 | flag = true; 24 | } 25 | 26 | } 27 | } 28 | 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | int arr[] = {9, 2, 1, 0, 3, 60, 35, 2, 45, 320, 5}; 34 | int arr2[] = {6,1,10,2,50,13,34,2,1,5,7,9}; 35 | 36 | System.out.println("Array 01 Before Improved Bubble Sort"); 37 | for (int i = 0; i < arr.length; i++) { 38 | System.out.print(arr[i] + " "); 39 | } 40 | System.out.println(); 41 | 42 | improvedBubbleSort(arr); 43 | 44 | System.out.println("Array After Improved Bubble Sort"); 45 | for (int i = 0; i < arr.length; i++) { 46 | System.out.print(arr[i] + " "); 47 | } 48 | 49 | System.out.println("Array 02 Before Improved Bubble Sort"); 50 | for (int i = 0; i < arr.length; i++) { 51 | System.out.print(arr2[i] + " "); 52 | } 53 | System.out.println(); 54 | 55 | improvedBubbleSort(arr2); 56 | 57 | System.out.println("Array After Improved Bubble Sort"); 58 | for (int i = 0; i < arr.length; i++) { 59 | System.out.print(arr2[i] + " "); 60 | } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Java/BucketSort.java: -------------------------------------------------------------------------------- 1 | public class BucketSort { 2 | 3 | static int[] sort(int[] nums, int max) { 4 | int[] bucket = new int[max + 1]; 5 | int[] sortedNums = new int[nums.length]; 6 | for (int i = 0; i < nums.length; i++) { 7 | bucket[nums[i]]++; 8 | } 9 | int index = 0; 10 | for (int i = 0; i < bucket.length; i++) { 11 | for (int j = 0; j < bucket[i]; j++) { 12 | sortedNums[index++] = i; 13 | } 14 | } 15 | return sortedNums; 16 | } 17 | 18 | static int getMax(int[] nums) { 19 | int max = 0; 20 | for (int i = 0; i < nums.length; i++) { 21 | if (nums[i] > max) { 22 | max = nums[i]; 23 | } 24 | } 25 | return max; 26 | } 27 | 28 | public static void main(String args[]) { 29 | int nums[] = {7, 3, 2, 1, 0, 4, 5}; 30 | int maxValue = getMax(nums); 31 | 32 | System.out.println("Unsorted Array:"); 33 | for (int i = 0; i < nums.length; i++) { 34 | System.out.print(nums[i] + " "); 35 | } 36 | 37 | nums = sort(nums, maxValue); 38 | 39 | System.out.println(); 40 | 41 | System.out.println("Sorted Array:"); 42 | for (int i = 0; i < nums.length; i++) { 43 | System.out.print(nums[i] + " "); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Java/CocktailSort.java: -------------------------------------------------------------------------------- 1 | public class CocktailSort { 2 | void cocktailSort(int a[]) 3 | { 4 | boolean swapped = true; 5 | int start = 0; 6 | int end = a.length; 7 | 8 | while (swapped == true) { 9 | // reset the swapped flag on entering the 10 | // loop, because it might be true from a 11 | // previous iteration. 12 | swapped = false; 13 | 14 | // loop from bottom to top same as 15 | // the bubble sort 16 | for (int i = start; i < end - 1; ++i) { 17 | if (a[i] > a[i + 1]) { 18 | int temp = a[i]; 19 | a[i] = a[i + 1]; 20 | a[i + 1] = temp; 21 | swapped = true; 22 | } 23 | } 24 | 25 | // if nothing moved, then array is sorted. 26 | if (swapped == false) 27 | break; 28 | 29 | // otherwise, reset the swapped flag so that it 30 | // can be used in the next stage 31 | swapped = false; 32 | 33 | // move the end point back by one, because 34 | // item at the end is in its rightful spot 35 | end = end - 1; 36 | 37 | // from top to bottom, doing the 38 | // same comparison as in the previous stage 39 | for (int i = end - 1; i >= start; i--) { 40 | if (a[i] > a[i + 1]) { 41 | int temp = a[i]; 42 | a[i] = a[i + 1]; 43 | a[i + 1] = temp; 44 | swapped = true; 45 | } 46 | } 47 | 48 | // increase the starting point, because 49 | // the last stage would have moved the next 50 | // smallest number to its rightful spot. 51 | start = start + 1; 52 | } 53 | } 54 | 55 | /* Prints the array */ 56 | void printArray(int a[]) 57 | { 58 | int n = a.length; 59 | for (int i = 0; i < n; i++) 60 | System.out.print(a[i] + " "); 61 | System.out.println(); 62 | } 63 | 64 | // Driver method 65 | public static void main(String[] args) 66 | { 67 | CocktailSort ob = new CocktailSort(); 68 | int a[] = { 5, 1, 4, 2, 8, 0, 2 }; 69 | ob.cocktailSort(a); 70 | System.out.println("Sorted array"); 71 | ob.printArray(a); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Java/CombSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * This class holds an example for a CombSort implementation with a main as an 5 | * example. 6 | * 7 | * Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. 8 | * So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size 9 | * more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration 10 | * until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap 11 | * and performs better than Bubble Sort. 12 | * 13 | * The shrink factor has been empirically found to be 1.3 14 | * 15 | */ 16 | 17 | public final class CombSort 18 | { 19 | // To find gap between elements 20 | static int getNextGap(int gap) 21 | { 22 | // Shrink gap by Shrink factor 23 | gap = (gap*10)/13; 24 | if (gap < 1) 25 | return 1; 26 | return gap; 27 | } 28 | 29 | // Function to sort arr[] using Comb Sort 30 | static void combSort(int arr[]) 31 | { 32 | int length = arr.length; 33 | 34 | // initialize gap 35 | int gap = length; 36 | 37 | // Initialize swapped as true to make sure that 38 | // loop runs 39 | boolean swapped = true; 40 | 41 | // Keep running while gap is more than 1 and last 42 | // iteration caused a swap 43 | while (gap != 1 || swapped == true) 44 | { 45 | // Find next gap 46 | gap = getNextGap(gap); 47 | 48 | // Initialize swapped as false so that we can 49 | // check if swap happened or not 50 | swapped = false; 51 | 52 | // Compare all elements with current gap 53 | for (int i=0; i arr[i+gap]) 56 | { 57 | // Swap arr[i] and arr[i+gap] 58 | int temp = arr[i]; 59 | arr[i] = arr[i+gap]; 60 | arr[i+gap] = temp; 61 | 62 | // Set swapped 63 | swapped = true; 64 | } 65 | } 66 | } 67 | } 68 | 69 | // Driver method 70 | public static void main(String args[]) 71 | { 72 | int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 73 | System.out.println(Arrays.toString(arr)); 74 | combSort(arr); 75 | System.out.println(Arrays.toString(arr)); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Java/Counting Sort.java: -------------------------------------------------------------------------------- 1 | // Counting sort which takes negative numbers as well 2 | import java.util.*; 3 | 4 | class GFG 5 | { 6 | 7 | static void countSort(int[] arr) 8 | { 9 | int max = Arrays.stream(arr).max().getAsInt(); 10 | int min = Arrays.stream(arr).min().getAsInt(); 11 | int range = max - min + 1; 12 | int count[] = new int[range]; 13 | int output[] = new int[arr.length]; 14 | for (int i = 0; i < arr.length; i++) 15 | { 16 | count[arr[i] - min]++; 17 | } 18 | 19 | for (int i = 1; i < count.length; i++) 20 | { 21 | count[i] += count[i - 1]; 22 | } 23 | 24 | for (int i = arr.length - 1; i >= 0; i--) 25 | { 26 | output[count[arr[i] - min] - 1] = arr[i]; 27 | count[arr[i] - min]--; 28 | } 29 | 30 | for (int i = 0; i < arr.length; i++) 31 | { 32 | arr[i] = output[i]; 33 | } 34 | } 35 | 36 | static void printArray(int[] arr) 37 | { 38 | System.out.println(Arrays.stream(arr) 39 | .mapToObj(String::valueOf) 40 | .collect(Collectors.joining(" "))); 41 | } 42 | 43 | // Driver code 44 | public static void main(String[] args) 45 | { 46 | int[] arr = {-5, -10, 0, -3, 8, 5, -1, 10}; 47 | countSort(arr); 48 | printArray(arr); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Java/CycleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | 4 | class CycleSort { 5 | // Function sort the array using Cycle sort 6 | public static void cycleSort(int arr[], int n) 7 | { 8 | // count number of memory writes 9 | int writes = 0; 10 | 11 | // traverse array elements and put it to on 12 | // the right place 13 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { 14 | // initialize item as starting point 15 | int item = arr[cycle_start]; 16 | 17 | // Find position where we put the item. We basically 18 | // count all smaller elements on right side of item. 19 | int pos = cycle_start; 20 | for (int i = cycle_start + 1; i < n; i++) 21 | if (arr[i] < item) 22 | pos++; 23 | 24 | // If item is already in correct position 25 | if (pos == cycle_start) 26 | continue; 27 | 28 | // ignore all duplicate elements 29 | while (item == arr[pos]) 30 | pos += 1; 31 | 32 | // put the item to it's right position 33 | if (pos != cycle_start) { 34 | int temp = item; 35 | item = arr[pos]; 36 | arr[pos] = temp; 37 | writes++; 38 | } 39 | 40 | // Rotate rest of the cycle 41 | while (pos != cycle_start) { 42 | pos = cycle_start; 43 | 44 | // Find position where we put the element 45 | for (int i = cycle_start + 1; i < n; i++) 46 | if (arr[i] < item) 47 | pos += 1; 48 | 49 | // ignore all duplicate elements 50 | while (item == arr[pos]) 51 | pos += 1; 52 | 53 | // put the item to it's right position 54 | if (item != arr[pos]) { 55 | int temp = item; 56 | item = arr[pos]; 57 | arr[pos] = temp; 58 | writes++; 59 | } 60 | } 61 | } 62 | } 63 | 64 | // Driver program to test above function 65 | public static void main(String[] args) 66 | { 67 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 68 | int n = arr.length; 69 | cycleSort(arr, n); 70 | 71 | System.out.println("After sort : "); 72 | for (int i = 0; i < n; i++) 73 | System.out.print(arr[i] + " "); 74 | } 75 | } -------------------------------------------------------------------------------- /Java/Decagonal_Numbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | A decagonal number is a figurate number that extends the concept of 3 | triangular and square numbers to the decagon (a ten-sided polygon). 4 | 5 | The n-th decagonal number is given by the formula: 6 | Dn = 4n^2 - 3n. 7 | */ 8 | 9 | import java.util.*; 10 | import java.util.Scanner; 11 | 12 | class Decagonal_Numbers 13 | { 14 | // To calculate decagonal number 15 | static int decagonalnumber (int num) 16 | { 17 | // Using formula 18 | return 4 * num * num - 3 * num; 19 | } 20 | 21 | public static void main(String[] args) 22 | { 23 | int num; 24 | Scanner sc = new Scanner(System.in); 25 | num = sc.nextInt(); 26 | System.out.println(num + " decagonal number : " + decagonalnumber(num)); 27 | } 28 | } 29 | 30 | /* 31 | Input: 32 | 6 33 | output: 34 | 6 decagonal number : 126 35 | */ 36 | -------------------------------------------------------------------------------- /Java/GnomeSort.java: -------------------------------------------------------------------------------- 1 | package Java; 2 | import java.util.Arrays; 3 | 4 | public class GnomeSort { 5 | 6 | public static void main(String[] args){ 7 | int[] arr = {1,6,23,5,8,2,43,35}; 8 | System.out.println(Arrays.toString(arr)); 9 | gnomeSort(arr); 10 | System.out.println(Arrays.toString(arr)); 11 | 12 | } 13 | 14 | 15 | private static void gnomeSort(int[] arr){ 16 | int pos = 0; 17 | int size = arr.length; 18 | while(pos < size){ 19 | if(pos == 0 || arr[pos] >= arr[pos-1]){ 20 | pos ++; 21 | } 22 | else{ 23 | swap(arr, pos, pos - 1); 24 | pos--; 25 | } 26 | } 27 | } 28 | 29 | private static void swap(int[] arr, int p1, int p2){ 30 | int temp = arr[p1]; 31 | arr[p1] = arr[p2]; 32 | arr[p2] = temp; 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Java/HeapSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Heap Sort 2 | public class HeapSort 3 | { 4 | public void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | 8 | // Build heap (rearrange array) 9 | for (int i = n / 2 - 1; i >= 0; i--) 10 | heapify(arr, n, i); 11 | 12 | // One by one extract an element from heap 13 | for (int i=n-1; i>=0; i--) 14 | { 15 | // Move current root to end 16 | int temp = arr[0]; 17 | arr[0] = arr[i]; 18 | arr[i] = temp; 19 | 20 | // call max heapify on the reduced heap 21 | heapify(arr, i, 0); 22 | } 23 | } 24 | 25 | // To heapify a subtree rooted with node i which is 26 | // an index in arr[]. n is size of heap 27 | void heapify(int arr[], int n, int i) 28 | { 29 | int largest = i; // Initialize largest as root 30 | int l = 2*i + 1; // left = 2*i + 1 31 | int r = 2*i + 2; // right = 2*i + 2 32 | 33 | // If left child is larger than root 34 | if (l < n && arr[l] > arr[largest]) 35 | largest = l; 36 | 37 | // If right child is larger than largest so far 38 | if (r < n && arr[r] > arr[largest]) 39 | largest = r; 40 | 41 | // If largest is not root 42 | if (largest != i) 43 | { 44 | int swap = arr[i]; 45 | arr[i] = arr[largest]; 46 | arr[largest] = swap; 47 | 48 | // Recursively heapify the affected sub-tree 49 | heapify(arr, n, largest); 50 | } 51 | } 52 | 53 | /* A utility function to print array of size n */ 54 | static void printArray(int arr[]) 55 | { 56 | int n = arr.length; 57 | for (int i=0; i= 0 && arr[j] > key) { 29 | arr[j + 1] = arr[j]; 30 | j = j - 1; 31 | } 32 | arr[j + 1] = key; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Java/MergeSort.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class MergeSort { 4 | @SuppressWarnings("unchecked") 5 | public static> void mergeSort(T[] arr) { 6 | if (arr.length == 1) { 7 | return; 8 | } 9 | int mid = arr.length/2; 10 | T[] l = (T[]) new Comparable[mid]; 11 | T[] r = (T[]) new Comparable[arr.length - mid]; 12 | for (int i = 0; i < mid; i++) { 13 | l[i] = arr[i]; 14 | } 15 | 16 | for (int i = mid; i < arr.length; i++) { 17 | r[i - mid] = arr[i]; 18 | } 19 | mergeSort(l); 20 | mergeSort(r); 21 | merge(arr, l, r); 22 | } 23 | 24 | private static> void merge(T[] arr, T[] leftArr, T[] rightArr) { 25 | int index = 0, i, j; 26 | for (i = 0, j = 0; i < leftArr.length && j < rightArr.length;) { 27 | if (leftArr[i].compareTo(rightArr[j]) <= 0) { 28 | arr[index++] = leftArr[i++]; 29 | } else { 30 | arr[index++] = rightArr[j++]; 31 | } 32 | } 33 | while (i < leftArr.length) { 34 | arr[index++] = leftArr[i++]; 35 | } 36 | while (j < rightArr.length) { 37 | arr[index++] = rightArr[j++]; 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | Integer[] arr = {5, 1, 3, 9, 23, 8, 7, 4}; 43 | mergeSort(arr); 44 | int[] sorted = new int[arr.length]; 45 | for (int i = 0; i < sorted.length; i++) { 46 | sorted[i] = arr[i]; 47 | } 48 | printArr(sorted); 49 | } 50 | 51 | private static void printArr(int[] arr) { 52 | for (int i : arr) { 53 | System.out.print(i + " "); 54 | } 55 | System.out.print("\n"); 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /Java/PancakeSort.java: -------------------------------------------------------------------------------- 1 | import static Sorts.SortUtils.*; 2 | 3 | public class PancakeSort implements SortAlgorithm { 4 | 5 | @Override 6 | public > T[] sort(T[] array) { 7 | int size = array.length; 8 | 9 | for (int i = 0; i < size; i++) { 10 | T max = array[0]; 11 | int index = 0; 12 | for (int j = 0; j < size - i; j++) { 13 | if (less(max, array[j])) { 14 | max = array[j]; 15 | index = j; 16 | } 17 | } 18 | flip(array, index, array.length - 1 - i); 19 | } 20 | return array; 21 | } 22 | 23 | 24 | public static void main(String[] args) { 25 | 26 | Integer[] arr = {10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1}; 27 | PancakeSort pancakeSort = new PancakeSort(); 28 | System.out.println("After sorting:"); 29 | pancakeSort.sort(arr); 30 | print(arr); 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Java/PigeonholeSort.java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | import java.util.*; 3 | 4 | public class PigeonholeSort 5 | { 6 | public static void pigeonhole_sort(int arr[], 7 | int n) 8 | { 9 | int min = arr[0]; 10 | int max = arr[0]; 11 | int range, i, j, index; 12 | 13 | for(int a=0; a max) 16 | max = arr[a]; 17 | if(arr[a] < min) 18 | min = arr[a]; 19 | } 20 | 21 | range = max - min + 1; 22 | int[] phole = new int[range]; 23 | Arrays.fill(phole, 0); 24 | 25 | for(i = 0; i0) 33 | arr[index++]=j+min; 34 | 35 | } 36 | 37 | public static void main(String[] args) 38 | { 39 | PigeonholeSort sort = new PigeonholeSort(); 40 | int[] arr = {8, 3, 2, 7, 4, 6, 8}; 41 | 42 | System.out.print("Sorted order is : "); 43 | 44 | sort.pigeonhole_sort(arr,arr.length); 45 | 46 | for(int i=0 ; i= high){ 25 | return; 26 | } 27 | 28 | //Get the pivot element from the middle of the list 29 | int middle = low + (high - low) / 2; 30 | int pivot = arr[middle]; 31 | 32 | // make left < pivot and right > pivot 33 | int i = low, j = high; 34 | while (i <= j) 35 | { 36 | //Check until all values on left side array are lower than pivot 37 | while (arr[i] < pivot) 38 | { 39 | i++; 40 | } 41 | //Check until all values on left side array are greater than pivot 42 | while (arr[j] > pivot) 43 | { 44 | j--; 45 | } 46 | //Now compare values from both side of lists to see if they need swapping 47 | //After swapping move the iterator on both lists 48 | if (i <= j) 49 | { 50 | swap (arr, i, j); 51 | i++; 52 | j--; 53 | } 54 | } 55 | //Do same operation as above recursively to sort two sub arrays 56 | if (low < j){ 57 | quickSort(arr, low, j); 58 | } 59 | if (high > i){ 60 | quickSort(arr, i, high); 61 | } 62 | } 63 | 64 | public static void swap (Integer array[], int x, int y) 65 | { 66 | int temp = array[x]; 67 | array[x] = array[y]; 68 | array[y] = temp; 69 | } 70 | } -------------------------------------------------------------------------------- /Java/RadixSort.java: -------------------------------------------------------------------------------- 1 | // Radix sort Java implementation 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class Radix { 6 | 7 | // A utility function to get maximum value in arr[] 8 | static int getMax(int arr[], int n) 9 | { 10 | int mx = arr[0]; 11 | for (int i = 1; i < n; i++) 12 | if (arr[i] > mx) 13 | mx = arr[i]; 14 | return mx; 15 | } 16 | 17 | // A function to do counting sort of arr[] according to 18 | // the digit represented by exp. 19 | static void countSort(int arr[], int n, int exp) 20 | { 21 | int output[] = new int[n]; // output array 22 | int i; 23 | int count[] = new int[10]; 24 | Arrays.fill(count,0); 25 | 26 | // Store count of occurrences in count[] 27 | for (i = 0; i < n; i++) 28 | count[ (arr[i]/exp)%10 ]++; 29 | 30 | // Change count[i] so that count[i] now contains 31 | // actual position of this digit in output[] 32 | for (i = 1; i < 10; i++) 33 | count[i] += count[i - 1]; 34 | 35 | // Build the output array 36 | for (i = n - 1; i >= 0; i--) 37 | { 38 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 39 | count[ (arr[i]/exp)%10 ]--; 40 | } 41 | 42 | // Copy the output array to arr[], so that arr[] now 43 | // contains sorted numbers according to curent digit 44 | for (i = 0; i < n; i++) 45 | arr[i] = output[i]; 46 | } 47 | 48 | // The main function to that sorts arr[] of size n using 49 | // Radix Sort 50 | static void radixsort(int arr[], int n) 51 | { 52 | // Find the maximum number to know number of digits 53 | int m = getMax(arr, n); 54 | 55 | // Do counting sort for every digit. Note that instead 56 | // of passing digit number, exp is passed. exp is 10^i 57 | // where i is current digit number 58 | for (int exp = 1; m/exp > 0; exp *= 10) 59 | countSort(arr, n, exp); 60 | } 61 | 62 | // A utility function to print an array 63 | static void print(int arr[], int n) 64 | { 65 | for (int i=0; i 0; gap /= 2) 20 | { 21 | // Do a gapped insertion sort for this gap size. 22 | // The first gap elements a[0..gap-1] are already 23 | // in gapped order keep adding one more element 24 | // until the entire array is gap sorted 25 | for (int i = gap; i < n; i += 1) 26 | { 27 | // add a[i] to the elements that have been gap 28 | // sorted save a[i] in temp and make a hole at 29 | // position i 30 | int temp = arr[i]; 31 | 32 | // shift earlier gap-sorted elements up until 33 | // the correct location for a[i] is found 34 | int j; 35 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 36 | arr[j] = arr[j - gap]; 37 | 38 | // put temp (the original a[i]) in its correct 39 | // location 40 | arr[j] = temp; 41 | } 42 | } 43 | return 0; 44 | } 45 | 46 | // Driver method 47 | public static void main(String args[]) 48 | { 49 | int arr[] = {12, 34, 54, 2, 3}; 50 | System.out.println("Array before sorting"); 51 | printArray(arr); 52 | 53 | ShellSort ob = new ShellSort(); 54 | ob.sort(arr); 55 | 56 | System.out.println("Array after sorting"); 57 | printArray(arr); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Java/TimSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | /** 4 | * This class holds an example for a Tim-Sort implementation with a main as an 5 | * example. 6 | * 7 | * 8 | * Timsort is a hybrid stable sorting algorithm, derived from merge sort and 9 | * insertion sort, designed to perform well on many kinds of real-world data. 10 | * Timsort was designed to take advantage of runs of consecutive ordered 11 | * elements that already exist in most real-world data, natural runs. It 12 | * iterates over the data collecting elements into runs, and simultaneously 13 | * merging those runs together. When there are runs, doing this decreases the 14 | * total number of comparisons needed to fully sort the list. 15 | * 16 | * 17 | * We divide the Array into blocks known as Run. We sort those runs using insertion sort 18 | * one by one and then merge those runs using combine function used in merge sort. 19 | * If the size of Array is less than run, then Array get sorted just by using Insertion Sort. 20 | * The size of run may vary from 32 to 64 depending upon the size of the array. 21 | * Note that merge function performs well when sizes subarrays are powers of 2. 22 | * The idea is based on the fact that insertion sort performs well for small arrays. 23 | */ 24 | 25 | public final class TimSort { 26 | 27 | static int RUN = 32; 28 | 29 | // this function sorts array from left index to 30 | // to right index which is of size atmost THREASHOLD 31 | public static void insertionSort(int[] arr, int left, int right) { 32 | for (int i = left + 1; i <= right; i++) { 33 | int temp = arr[i]; 34 | int j = i - 1; 35 | while (j >= 0 && arr[j] > temp && j >= left) { 36 | arr[j + 1] = arr[j]; 37 | j--; 38 | } 39 | arr[j + 1] = temp; 40 | } 41 | } 42 | 43 | // merge function merges the sorted runs 44 | public static void merge(int[] arr, int left, int mid, int right) { 45 | 46 | int leftArryLen = mid - left + 1, rightArrLen = right - mid; 47 | int[] leftArr = new int[leftArryLen]; 48 | int[] rightArr = new int[rightArrLen]; 49 | 50 | for (int x = 0; x < leftArryLen; x++) { 51 | leftArr[x] = arr[left + x]; 52 | } 53 | 54 | for (int x = 0; x < rightArrLen; x++) { 55 | rightArr[x] = arr[mid + 1 + x]; 56 | } 57 | 58 | int i = 0; 59 | int j = 0; 60 | int k = left; 61 | 62 | while (i < leftArryLen && j < rightArrLen) { 63 | if (leftArr[i] <= rightArr[j]) { 64 | arr[k] = leftArr[i]; 65 | i++; 66 | } else { 67 | arr[k] = rightArr[j]; 68 | j++; 69 | } 70 | k++; 71 | } 72 | 73 | // copy remaining elements of left, if any 74 | while (i < leftArryLen) { 75 | arr[k] = leftArr[i]; 76 | k++; 77 | i++; 78 | } 79 | 80 | // copy remaining element of right, if any 81 | while (j < rightArrLen) { 82 | arr[k] = rightArr[j]; 83 | k++; 84 | j++; 85 | } 86 | } 87 | 88 | public static void timSort(int[] arr) { 89 | int length = arr.length; 90 | 91 | // Sort individual subarrays of size THRESHOLD 92 | for (int i = 0; i < length; i += RUN) { 93 | // perform insertion sort 94 | insertionSort(arr, i, Math.min((i + 31), (length - 1))); 95 | } 96 | 97 | for (int size = RUN; size < length; size = 2 * size) { 98 | for (int left = 0; left < length; left += 2 * size) { 99 | int mid = left + size - 1; 100 | int right = Math.min((left + 2 * size - 1), (length - 1)); 101 | // perform merge sort 102 | merge(arr, left, mid, right); 103 | } 104 | } 105 | } 106 | 107 | public static void main(String[] args) { 108 | int[] arr = { 10, 3, 2, 19, 7, 15, 23, 13, 1 }; 109 | System.out.println(Arrays.toString(arr)); 110 | timSort(arr); 111 | System.out.println(Arrays.toString(arr)); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Java/TopologicalSort.java: -------------------------------------------------------------------------------- 1 | // Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering 2 | // of vertices such that for every directed edge uv, vertex u comes before v in the ordering. 3 | // Topological Sorting for a graph is not possible if the graph is not a DAG. 4 | 5 | // Resources : 6 | // https://en.wikipedia.org/wiki/Topological_sorting 7 | // https://www.geeksforgeeks.org/topological-sorting/ 8 | 9 | import java.util.ArrayList; 10 | import java.util.HashMap; 11 | import java.util.Stack; 12 | 13 | //Time complexity : O(V + E) 14 | //V : number of vertices of the graph 15 | //E : number of edges of the graph 16 | 17 | public class TopologicalSort { 18 | //Graph class implemented with adjacency list method 19 | //resource : https://www.geeksforgeeks.org/graph-and-its-representations/ 20 | static class Graph { 21 | int N; 22 | ArrayList> list; 23 | public Graph(int v) { 24 | N = v; 25 | list = new ArrayList<>(v); 26 | for(int i = 0; i < v; i++) 27 | list.add(new ArrayList<>()); 28 | } 29 | public void addEdge(int v1, int v2) { 30 | list.get(v1).add(v2); 31 | } 32 | } 33 | static void dfs(Graph g, Integer i, HashMap visited, 34 | Stack stack) { 35 | visited.put(i, true); 36 | ArrayList neighbors = g.list.get(i); 37 | for(Integer x : neighbors) 38 | if(!visited.get(x)) 39 | dfs(g, x, visited, stack); 40 | stack.push(i); 41 | } 42 | static ArrayList topologicalSort(Graph g) { 43 | HashMap visited = new HashMap<>(); 44 | Stack stack = new Stack<>(); 45 | ArrayList output = new ArrayList<>(); 46 | for(int x = 0; x < g.N; x++) 47 | visited.put(x, false); 48 | 49 | for(int i = 0; i < g.N; i++) { 50 | if(!visited.get(i)) 51 | dfs(g, i, visited, stack); 52 | } 53 | 54 | while(!stack.empty()) { 55 | int temp = stack.pop(); 56 | output.add(temp); 57 | } 58 | return output; 59 | } 60 | //driver method 61 | public static void main(String[] args) { 62 | //The directed acyclic graph that is created here: 63 | // 5 ------> 0 <-------- 4 64 | // | | 65 | // | | 66 | // | | 67 | // \|/ \|/ 68 | // * * 69 | // 2 ------> 3 --------> 1 70 | Graph g = new Graph(6); 71 | g.addEdge(5, 2); 72 | g.addEdge(5, 0); 73 | g.addEdge(4, 0); 74 | g.addEdge(4, 1); 75 | g.addEdge(2, 3); 76 | g.addEdge(3, 1); 77 | 78 | ArrayList sorted = topologicalSort(g); 79 | for(Integer x : sorted) { 80 | System.out.print(x+" "); 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /Java/TreeSort.java: -------------------------------------------------------------------------------- 1 | 2 | class TreeSort 3 | { 4 | // Class containing left and 5 | // right child of current 6 | // node and key value 7 | class Node 8 | { 9 | int key; 10 | Node left, right; 11 | 12 | public Node(int item) 13 | { 14 | key = item; 15 | left = right = null; 16 | } 17 | } 18 | 19 | // Root of BST 20 | Node root; 21 | 22 | // Constructor 23 | TreeSort() 24 | { 25 | root = null; 26 | } 27 | 28 | // This method mainly 29 | // calls insertRec() 30 | void insert(int key) 31 | { 32 | root = insertRec(root, key); 33 | } 34 | 35 | /* A recursive function to 36 | insert a new key in BST */ 37 | Node insertRec(Node root, int key) 38 | { 39 | 40 | /* If the tree is empty, 41 | return a new node */ 42 | if (root == null) 43 | { 44 | root = new Node(key); 45 | return root; 46 | } 47 | 48 | /* Otherwise, recur 49 | down the tree */ 50 | if (key < root.key) 51 | root.left = insertRec(root.left, key); 52 | else if (key > root.key) 53 | root.right = insertRec(root.right, key); 54 | 55 | /* return the root */ 56 | return root; 57 | } 58 | 59 | // A function to do 60 | // inorder traversal of BST 61 | void inorderRec(Node root) 62 | { 63 | if (root != null) 64 | { 65 | inorderRec(root.left); 66 | System.out.print(root.key + " "); 67 | inorderRec(root.right); 68 | } 69 | } 70 | void treeins(int arr[]) 71 | { 72 | for(int i = 0; i < arr.length; i++) 73 | { 74 | insert(arr[i]); 75 | } 76 | 77 | } 78 | 79 | // Driver Code 80 | public static void main(String[] args) 81 | { 82 | TreeSort tree = new TreeSort(); 83 | int arr[] = {5, 4, 7, 2, 11}; 84 | tree.treeins(arr); 85 | tree.inorderRec(tree.root); 86 | } 87 | } -------------------------------------------------------------------------------- /Javascript/HeapSort.js: -------------------------------------------------------------------------------- 1 | function heapSort(arr){ 2 | var len = arr.length, 3 | end = len-1; 4 | 5 | heapify(arr, len); 6 | 7 | while(end > 0){ 8 | swap(arr, end--, 0); 9 | DownHeapify(arr, 0, end); 10 | } 11 | return arr; 12 | } 13 | 14 | function heapify(arr, len){ 15 | // breaking the array into root + two sides, to create tree (heap) 16 | var mid = Math.floor((len-2)/2); 17 | while(mid >= 0){ 18 | DownHeapify(arr, mid--, len-1); 19 | } 20 | } 21 | 22 | function DownHeapify(arr, start, end){ 23 | var root = start, 24 | child = root*2 + 1, 25 | toSwap = root; 26 | while(child <= end){ 27 | if(arr[toSwap] < arr[child]){ 28 | swap(arr, toSwap, child); 29 | } 30 | if(child+1 <= end && arr[toSwap] < arr[child+1]){ 31 | swap(arr, toSwap, child+1) 32 | } 33 | if(toSwap != root){ 34 | swap(arr, root, toSwap); 35 | root = toSwap; 36 | } 37 | else{ 38 | return; 39 | } 40 | toSwap = root; 41 | child = root*2+1 42 | } 43 | } 44 | 45 | 46 | function swap(arr, i, j){ 47 | var temp = arr[i]; 48 | arr[i] = arr[j]; 49 | arr[j] = temp; 50 | } -------------------------------------------------------------------------------- /Javascript/Insertionsort.js: -------------------------------------------------------------------------------- 1 | const insertionSort = arr => { 2 | const len = arr.length; 3 | for (let i = 0; i < len; i++) { 4 | let el = arr[i]; 5 | let j; 6 | 7 | for (j = i - 1; j >= 0 && arr[j] > el; j--) { 8 | arr[j + 1] = arr[j]; 9 | } 10 | arr[j + 1] = el; 11 | } 12 | return arr; 13 | }; -------------------------------------------------------------------------------- /Javascript/MergeSort.js: -------------------------------------------------------------------------------- 1 | function mergeSort (arr) { 2 | if (arr.length < 2) { 3 | return arr; 4 | } 5 | 6 | var mid = Math.floor(arr.length / 2); 7 | var subLeft = mergeSort(arr.slice(0, mid)); 8 | var subRight = mergeSort(arr.slice(mid)); 9 | 10 | return merge(subLeft, subRight); 11 | } 12 | 13 | function merge (node1, node2) { 14 | var result = []; 15 | while (node1.length > 0 && node2.length > 0) 16 | result.push(node1[0] < node2[0] ? node1.shift() : node2.shift()); 17 | return result.concat(node1.length ? node1 : node2); 18 | } -------------------------------------------------------------------------------- /Javascript/Quicksort.js: -------------------------------------------------------------------------------- 1 | function quickSort(arr, left, right){ 2 | var len = arr.length, 3 | pivot, 4 | partitionIndex; 5 | 6 | 7 | if(left < right){ 8 | pivot = right; 9 | partitionIndex = partition(arr, pivot, left, right); 10 | 11 | //sort left and right 12 | quickSort(arr, left, partitionIndex - 1); 13 | quickSort(arr, partitionIndex + 1, right); 14 | } 15 | return arr; 16 | } 17 | 18 | function partition(arr, pivot, left, right){ 19 | var pivotValue = arr[pivot], 20 | partitionIndex = left; 21 | 22 | for(var i = left; i < right; i++){ 23 | if(arr[i] < pivotValue){ 24 | swap(arr, i, partitionIndex); 25 | partitionIndex++; 26 | } 27 | } 28 | swap(arr, right, partitionIndex); 29 | return partitionIndex; 30 | } 31 | 32 | function swap(arr, i, j){ 33 | var temp = arr[i]; 34 | arr[i] = arr[j]; 35 | arr[j] = temp; 36 | } 37 | -------------------------------------------------------------------------------- /Javascript/RadixSort.js: -------------------------------------------------------------------------------- 1 | var testArray = [ 31, 654, 222, 74, 689, 45, 89, 223, 345, 145, 8 ]; 2 | 3 | function radixBucketSort (arr) { 4 | var idx1, idx2, idx3, len1, len2, radix, radixKey; 5 | var radices = {}, buckets = {}, num, curr; 6 | var currLen, radixStr, currBucket; 7 | 8 | len1 = arr.length; 9 | len2 = 10; // radix sort uses ten buckets 10 | 11 | // find the relevant radices to process for efficiency 12 | for (idx1 = 0;idx1 < len1;idx1++) { 13 | radices[arr[idx1].toString().length] = 0; 14 | } 15 | 16 | // loop for each radix. For each radix we put all the items 17 | // in buckets, and then pull them out of the buckets. 18 | for (radix in radices) { 19 | // put each array item in a bucket based on its radix value 20 | len1 = arr.length; 21 | for (idx1 = 0;idx1 < len1;idx1++) { 22 | curr = arr[idx1]; 23 | // item length is used to find its current radix value 24 | currLen = curr.toString().length; 25 | // only put the item in a radix bucket if the item 26 | // key is as long as the radix 27 | if (currLen >= radix) { 28 | // radix starts from beginning of key, so need to 29 | // adjust to get redix values from start of stringified key 30 | radixKey = curr.toString()[currLen - radix]; 31 | // create the bucket if it does not already exist 32 | if (!buckets.hasOwnProperty(radixKey)) { 33 | buckets[radixKey] = []; 34 | } 35 | // put the array value in the bucket 36 | buckets[radixKey].push(curr); 37 | } else { 38 | if (!buckets.hasOwnProperty('0')) { 39 | buckets['0'] = []; 40 | } 41 | buckets['0'].push(curr); 42 | } 43 | } 44 | // for current radix, items are in buckets, now put them 45 | // back in the array based on their buckets 46 | // this index moves us through the array as we insert items 47 | idx1 = 0; 48 | // go through all the buckets 49 | for (idx2 = 0;idx2 < len2;idx2++) { 50 | // only process buckets with items 51 | if (buckets[idx2] != null) { 52 | currBucket = buckets[idx2]; 53 | // insert all bucket items into array 54 | len1 = currBucket.length; 55 | for (idx3 = 0;idx3 < len1;idx3++) { 56 | arr[idx1++] = currBucket[idx3]; 57 | } 58 | } 59 | } 60 | buckets = {}; 61 | } 62 | } 63 | radixBucketSort(testArray); -------------------------------------------------------------------------------- /Javascript/TopologicalSort.js: -------------------------------------------------------------------------------- 1 | function tsort(edges) { 2 | let nodes = {}, // hash: stringified id of the node => { id: id, afters: lisf of ids } 3 | sorted = [], // sorted list of IDs ( returned value ) 4 | visited = {}; // hash: id of already visited node => true 5 | 6 | let Node = function(id) { 7 | this.id = id; 8 | this.afters = []; 9 | } 10 | 11 | edges.forEach(function(v) { 12 | let from = v[0], to = v[1]; 13 | if (!nodes[from]) nodes[from] = new Node(from); 14 | if (!nodes[to]) nodes[to] = new Node(to); 15 | nodes[from].afters.push(to); 16 | }); 17 | 18 | // Main topological sort happens here 19 | Object.keys(nodes).forEach(function visit(idstr, ancestors) { 20 | let node = nodes[idstr], 21 | id = node.id; 22 | 23 | // if already exists, do nothing 24 | if (visited[idstr]) return; 25 | 26 | if (!Array.isArray(ancestors)) ancestors = []; 27 | 28 | ancestors.push(id); 29 | 30 | visited[idstr] = true; 31 | 32 | node.afters.forEach(function(afterID) { 33 | if (ancestors.indexOf(afterID) >= 0) // if already in ancestors, a closed chain exists. 34 | throw new Error('closed chain : ' + afterID + ' is in ' + id); 35 | 36 | visit(afterID.toString(), ancestors.map(function(v) { return v })); // recursive call 37 | }); 38 | 39 | sorted.unshift(id); 40 | }); 41 | 42 | return sorted; 43 | } -------------------------------------------------------------------------------- /Javascript/bogoSort.js: -------------------------------------------------------------------------------- 1 | function isSorted(arr) { 2 | if (arr.length == 0 || arr.length == 1) { 3 | return true; 4 | } 5 | 6 | for (let i=0;i arr[i+1]) { 8 | return false; 9 | } 10 | } 11 | 12 | return true; 13 | } 14 | 15 | function shuffleArray(array) { 16 | for (let i = array.length - 1; i > 0; i--) { 17 | const j = Math.floor(Math.random() * (i + 1)); 18 | [array[i], array[j]] = [array[j], array[i]]; 19 | } 20 | return array; 21 | } 22 | 23 | function bogoSort(data) { 24 | while (!isSorted(data)) { 25 | data = shuffleArray(data); 26 | }; 27 | return data; 28 | } -------------------------------------------------------------------------------- /Javascript/bubbleSort.js: -------------------------------------------------------------------------------- 1 | const bubbleSort = (numArray) => { 2 | let rotated; 3 | do { 4 | rotated = false; 5 | for (let i = 0; i < numArray.length-1; i++) { 6 | if (numArray[i] > numArray[i+1]) { 7 | store = numArray[i]; 8 | numArray[i] = numArray[i+1]; 9 | numArray[i+1] = store; 10 | rotated = true; 11 | } 12 | } 13 | } while (rotated === true) 14 | return numArray 15 | } 16 | -------------------------------------------------------------------------------- /Javascript/countingSort.js: -------------------------------------------------------------------------------- 1 | function counntingSort(arr, min, max) { 2 | let i = min, 3 | j = 0, 4 | len = arr.length, 5 | count = []; 6 | 7 | for (i; i <= max; i++) { 8 | count[i] = 0; 9 | } 10 | 11 | for (i = 0; i < len; i++) { 12 | count[arr[i]] += 1; 13 | } 14 | 15 | for (i = min; i <= max; i++) { 16 | while (count[i] > 0) { 17 | arr[j] = i; 18 | j++; 19 | count[i]--; 20 | } 21 | } 22 | 23 | return arr; 24 | } -------------------------------------------------------------------------------- /Javascript/gnomeSort.js: -------------------------------------------------------------------------------- 1 | const swapElements = (arr, i, j) => { 2 | const tmp = arr[i]; 3 | arr[i] = arr[j]; 4 | arr[j] = tmp; 5 | }; 6 | 7 | const gnomeSort = arr => { 8 | let pos = 0; 9 | while (pos < arr.length) { 10 | if (pos === 0 || arr[pos] >= arr[pos - 1]) { 11 | pos++; 12 | } else { 13 | swapElements(arr, pos, pos - 1); 14 | pos--; 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Javascript/selectionSort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(A) { 2 | var len = array_length(A); 3 | for (var i = 0; i < len - 1; i = i + 1) { 4 | var j_min = i; 5 | for (var j = i + 1; j < len; j = j + 1) { 6 | if (A[j] < A[j_min]) { 7 | j_min = j; 8 | } else {} 9 | } 10 | if (j_min !== i) { 11 | swap(A, i, j_min); 12 | } else {} 13 | } 14 | } 15 | 16 | function swap(A, x, y) { 17 | var temp = A[x]; 18 | A[x] = A[y]; 19 | A[y] = temp; 20 | } -------------------------------------------------------------------------------- /Javascript/shellSort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Shell sort or Shell's method, is an in-place comparison sort. It can be seen as 3 | * either a generalization of sorting by exchange (bubble sort) or sorting by 4 | * insertion (insertion sort). The method starts by sorting pairs of elements 5 | * far apart from each other, then progressively reducing the gap between elements 6 | * to be compared. Starting with far apart elements can move some out-of-place elements 7 | * into position faster than a simple nearest neighbor exchange 8 | */ 9 | 10 | function shellSort(arr) { 11 | let increment = arr.length / 2; 12 | while (increment > 0) { 13 | for (i = increment; i < arr.length; i++) { 14 | let j = i; 15 | let temp = arr[i]; 16 | 17 | while (j >= increment && arr[j-increment] > temp) { 18 | arr[j] = arr[j-increment]; 19 | j = j - increment; 20 | } 21 | 22 | arr[j] = temp; 23 | } 24 | 25 | if (increment == 2) { 26 | increment = 1; 27 | } else { 28 | increment = parseInt(increment*5 / 11); 29 | } 30 | } 31 | return arr; 32 | } -------------------------------------------------------------------------------- /Kotlin/BogoSort.kt: -------------------------------------------------------------------------------- 1 | import kotlin.random.Random 2 | 3 | fun main(args : Array) { 4 | //Create Array 5 | var array = intArrayOf(4,5,3,9,1) 6 | 7 | array = sort(array) 8 | 9 | array.forEach { 10 | println(it) 11 | } 12 | } 13 | 14 | /** 15 | * Use Bogo sort to randomly swap two inputs and then check if the list is sorted 16 | */ 17 | fun sort(input:IntArray):IntArray{ 18 | 19 | //keep repeating check until sorted 20 | while (!isSorted(input)){ 21 | //get two randomly picked array locations 22 | val index1 = Random.nextInt(0, input.size-1) 23 | val index2 = Random.nextInt(0, input.size-1) 24 | 25 | //swap the values 26 | val temp = input[index1] 27 | input[index1] = input[index2] 28 | input[index2] = temp 29 | } 30 | return input 31 | } 32 | 33 | /** 34 | * Check if the array is sorted from lowest to highest 35 | */ 36 | fun isSorted(input:IntArray): Boolean{ 37 | var max:Int? = null 38 | for(x in input.indices){ 39 | if(max == null || input[x] >= max){ 40 | max = input[x] 41 | }else{ 42 | return false 43 | } 44 | } 45 | return true 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Kotlin/BubbleSort.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun input(): Array{ 4 | //instance of Scanner class 5 | val reader: Scanner = Scanner(System.`in`) 6 | 7 | //creating the array 8 | println("enter size of array : ") 9 | var size:Int=reader.nextInt() 10 | var myArray=Array(size){0} 11 | 12 | //initializing the array 13 | for (i in 0..(size-1)){ 14 | print("\nEnter element : ") 15 | myArray.set(i,reader.nextInt()) 16 | } 17 | 18 | return myArray 19 | } 20 | 21 | fun display(myArray: Array){ 22 | for (element in myArray) 23 | print(" "+ element) 24 | } 25 | 26 | fun main(args: Array){ 27 | var array=input() 28 | println("array before sorting : ") 29 | display(array) 30 | array=bubbleSort(array) 31 | println("\narray after sorting : ") 32 | display(array) 33 | 34 | } 35 | 36 | fun bubbleSort(array: Array): Array { 37 | 38 | for(i in 0..(array.size-2)) 39 | for (j in 0..(array.size-2-i)){ 40 | if(array.get(j+1)) { 2 | val sorted = cocktailShakerSort(intArrayOf(4, 4, -4, 751, 7, 9, 5, 37564, -54, 1, 0, 100)) 3 | sorted.forEach { 4 | print("$it, ") 5 | } 6 | } 7 | 8 | fun cocktailShakerSort(input:IntArray):IntArray{ 9 | if(input.size <= 1){ 10 | return input 11 | } 12 | 13 | var start = 0 14 | var end = input.size -2 15 | var unsorted = true 16 | 17 | 18 | while(unsorted) { 19 | unsorted = false 20 | 21 | for (i in start..end) { 22 | if (input[i] > input[i + 1]) { 23 | val temp = input[i + 1] 24 | input[i + 1] = input[i] 25 | input[i] = temp 26 | unsorted = true 27 | } 28 | } 29 | 30 | if (!unsorted) { 31 | break 32 | } else { 33 | unsorted = false 34 | end-- 35 | 36 | for (i in end downTo start) { 37 | if (input[i] > input[i + 1]) { 38 | val temp = input[i + 1] 39 | input[i + 1] = input[i] 40 | input[i] = temp 41 | unsorted = true 42 | } 43 | } 44 | start++ 45 | } 46 | } 47 | 48 | 49 | return input 50 | } -------------------------------------------------------------------------------- /Kotlin/CountingSort.kt: -------------------------------------------------------------------------------- 1 | fun main(args : Array) { 2 | val sorted = countingSort(intArrayOf(4, 4, -4, 1, 7, 9, 5, 37564, -54, 0, 100)) 3 | sorted.forEach { 4 | print("$it, ") 5 | } 6 | } 7 | 8 | * Kotlin Counting Sort that allows for negative numbers. 9 | */ 10 | fun countingSort(input:IntArray):IntArray{ 11 | if(input.size == 1){ 12 | return input 13 | } 14 | //max value in range 15 | val max= input.max() 16 | //min value in range 17 | val min = input.min() 18 | //the range of the values 19 | val len = max!! - min!! + 1 20 | 21 | //Array for counting the number of occurrences of each value 22 | var count = IntArray(len) 23 | //Output array to store the sorted array 24 | var output = IntArray(input.size) 25 | 26 | 27 | input.forEach { value -> 28 | //Use Min to index the values into the correct spot in array 29 | var currentCount = count[value - min] 30 | currentCount++ 31 | count[value - min] = currentCount 32 | } 33 | 34 | //location in the output array 35 | var pointer = 0 36 | for(j in count.indices){ //Uses For loop rather than foreach to preserve the location in the count array. 37 | for (i in 0..count[j]){ 38 | if(count[j] != 0) { 39 | output[pointer] = j+min 40 | pointer++ 41 | count[j]-- 42 | } 43 | } 44 | } 45 | return output 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Kotlin/HeapSort.kt: -------------------------------------------------------------------------------- 1 | 2 | class HeapSort { 3 | fun sort(arr: IntArray) { 4 | val n = arr.size 5 | 6 | // Build heap (rearrange array) 7 | for (i in n / 2 - 1 downTo 0) 8 | heapify(arr, n, i) 9 | 10 | // One by one extract an element from heap 11 | for (i in n - 1 downTo 0) { 12 | // Move current root to end 13 | val temp = arr[0] 14 | arr[0] = arr[i] 15 | arr[i] = temp 16 | 17 | // call max heapify on the reduced heap 18 | heapify(arr, i, 0) 19 | } 20 | } 21 | 22 | // To heapify a subtree rooted with node i which is 23 | // an index in arr[]. n is size of heap 24 | internal fun heapify(arr: IntArray, n: Int, i: Int) { 25 | var largest = i // Initialize largest as root 26 | val l = 2 * i + 1 // left = 2*i + 1 27 | val r = 2 * i + 2 // right = 2*i + 2 28 | 29 | // If left child is larger than root 30 | if (l < n && arr[l] > arr[largest]) 31 | largest = l 32 | 33 | // If right child is larger than largest so far 34 | if (r < n && arr[r] > arr[largest]) 35 | largest = r 36 | 37 | // If largest is not root 38 | if (largest != i) { 39 | val swap = arr[i] 40 | arr[i] = arr[largest] 41 | arr[largest] = swap 42 | 43 | // Recursively heapify the affected sub-tree 44 | heapify(arr, n, largest) 45 | } 46 | } 47 | 48 | companion object { 49 | 50 | /* A utility function to print array of size n */ 51 | internal fun printArray(arr: IntArray) { 52 | val n = arr.size 53 | for (i in 0 until n) 54 | print(arr[i].toString() + " ") 55 | println() 56 | } 57 | 58 | // Driver program 59 | @JvmStatic 60 | fun main(args: Array) { 61 | val arr = intArrayOf(12, 11, 13, 5, 6, 7) 62 | val n = arr.size 63 | 64 | val ob = HeapSort() 65 | ob.sort(arr) 66 | 67 | println("Sorted array is") 68 | printArray(arr) 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Kotlin/InsertionSort.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun inputArr(): Array{ 4 | //instance of Scanner class 5 | val reader: Scanner = Scanner(System.`in`) 6 | 7 | //creating the array 8 | println("enter size of array : ") 9 | var size:Int=reader.nextInt() 10 | var myArray=Array(size){0} 11 | 12 | //initializing the array 13 | for (i in 0 until size-1){ 14 | print("\nEnter element : ") 15 | myArray.set(i,reader.nextInt()) 16 | } 17 | 18 | return myArray 19 | } 20 | 21 | fun displayArr(myArray: Array){ 22 | for (element in myArray) 23 | print(" $element") 24 | } 25 | 26 | fun main(args: Array){ 27 | var array=input() 28 | println("array before sorting : ") 29 | display(array) 30 | array=insertionSort(array) 31 | println("\narray after sorting : ") 32 | display(array) 33 | 34 | } 35 | 36 | fun insertionSort(array: Array): Array { 37 | val n = array.size; 38 | for (i in 1 until n-1) { 39 | var key = array.get(i); 40 | var j = i - 1; 41 | 42 | /* Move elements of arr[0..i-1], that are 43 | greater than key, to one position ahead 44 | of their current position */ 45 | while (j >= 0 && array[j] > key) { 46 | 47 | array[j+1] = array[j]; 48 | j -= 1; 49 | } 50 | array[j+1] = key; 51 | } 52 | 53 | return array 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Kotlin/MergeSort.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by jens on 3/8/17. 3 | */ 4 | 5 | fun mergeSort(list: List): List { 6 | if (list.size <= 1) { 7 | return list 8 | } 9 | 10 | val middle = list.size / 2 11 | var left = list.subList(0,middle); 12 | var right = list.subList(middle,list.size); 13 | 14 | return merge(mergeSort(left), mergeSort(right)) 15 | } 16 | 17 | 18 | fun merge(left: List, right: List): List { 19 | var indexLeft = 0 20 | var indexRight = 0 21 | var newList : MutableList = mutableListOf() 22 | 23 | while (indexLeft < left.count() && indexRight < right.count()) { 24 | if (left[indexLeft] <= right[indexRight]) { 25 | newList.add(left[indexLeft]) 26 | indexLeft++ 27 | } else { 28 | newList.add(right[indexRight]) 29 | indexRight++ 30 | } 31 | } 32 | 33 | while (indexLeft < left.size) { 34 | newList.add(left[indexLeft]) 35 | indexLeft++ 36 | } 37 | 38 | while (indexRight < right.size) { 39 | newList.add(right[indexRight]) 40 | indexRight++ 41 | } 42 | 43 | return newList; 44 | } 45 | 46 | fun main(args: Array) { 47 | val numbers = mutableListOf(38,27,43,3,9,82,10) 48 | val sortedList = mergeSort(numbers) 49 | println("Unsorted: $numbers") 50 | println("Sorted: $sortedList") 51 | } -------------------------------------------------------------------------------- /Kotlin/QuickSort.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() 3 | quickSort(array, 0, array.size-1) 4 | for(i in array) println(i) 5 | } 6 | 7 | fun quickSort(array: IntArray, left: Int, right: Int) { 8 | val index = partition (array, left, right) 9 | if(left < index-1) { 10 | quickSort(array, left, index-1) 11 | } 12 | if(index < right) { 13 | quickSort(array,index, right) 14 | } 15 | } 16 | 17 | fun partition(array: IntArray, l: Int, r: Int): Int { 18 | var left = l 19 | var right = r 20 | val pivot = array[(left + right)/2] 21 | while (left <= right) { 22 | while (array[left] < pivot) left++ 23 | 24 | while (array[right] > pivot) right-- 25 | 26 | if (left <= right) { 27 | swapArray(array, left,right) 28 | left++ 29 | right-- 30 | } 31 | } 32 | return left 33 | } 34 | 35 | fun swapArray(a: IntArray, b: Int, c: Int) { 36 | val temp = a[b] 37 | a[b] = a[c] 38 | a[c] = temp 39 | } 40 | -------------------------------------------------------------------------------- /Kotlin/RadixSort.kt: -------------------------------------------------------------------------------- 1 | fun main(args : Array) { 2 | val sorted = radixSort(intArrayOf(4, 4, 4, 1, 7, 9, 5, 37564, 54, 0, 100)) 3 | sorted.forEach { 4 | print("$it, ") 5 | } 6 | } 7 | 8 | /** 9 | * Sorts positive numbers only using Radix Sort 10 | */ 11 | fun radixSort(input:IntArray):IntArray { 12 | var out = input 13 | val max = input.max() 14 | 15 | var exp = 1 16 | while (max!!.div(exp) > 0) { //Loops through each place starting with the 0's place before incrementing 17 | out = countingRadixSort(out, exp) 18 | exp *= 10 19 | } 20 | 21 | return out 22 | } 23 | 24 | fun countingRadixSort(input:IntArray, exp:Int):IntArray{ 25 | if(input.size == 1) { 26 | return input 27 | } 28 | 29 | //Array for counting the number of occurrences of each value 30 | var count = Array>(10){ArrayList()} 31 | //Output array to store the sorted array 32 | var output = IntArray(input.size) 33 | 34 | //Stores each value in the array list corresponding with the value being checked in this round. 35 | input.forEach { value -> 36 | val radix = value.div(exp)%10 37 | count[radix].add(value) 38 | } 39 | 40 | var pointer = 0 41 | for(i in count.indices){ //Uses For loop rather than foreach to preserve the location in the count array. 42 | count[i].forEach { 43 | output[pointer] = it 44 | pointer++ 45 | } 46 | } 47 | return output 48 | } -------------------------------------------------------------------------------- /Kotlin/insertionSort.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun insertionsort(items:MutableList):List{ 4 | if (items.isEmpty() || items.size<2){ 5 | return items 6 | } 7 | for (count in 1..items.count() - 1){ 8 | // println(items) 9 | val item = items[count] 10 | var i = count 11 | while (i>0 && item < items[i - 1]){ 12 | items[i] = items[i - 1] 13 | i -= 1 14 | } 15 | items[i] = item 16 | } 17 | return items 18 | } 19 | fun main(args: Array) { 20 | val names = mutableListOf(8, 3, 2, 7, 4) 21 | println(names) 22 | var ordered = insertionsort(names) 23 | println(ordered) 24 | } 25 | -------------------------------------------------------------------------------- /Kotlin/selectionSort.kt: -------------------------------------------------------------------------------- 1 | fun selectionSort(A:Array){ 2 | var n = A.size 3 | var temp: Int 4 | for(i in n-1 downTo 0){ 5 | var max = i 6 | for(j in 0 until i){ 7 | if(A[j] > A[max]) 8 | max = j 9 | } 10 | if(i != max){ 11 | temp = A[i] 12 | A[i]= A[max] 13 | A[max] = temp 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 hadshirt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python/BinaryInsertionSort.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, val, start, end): 2 | # we need to distinugish whether we should insert 3 | # before or after the left boundary. 4 | # imagine [0] is the last step of the binary search 5 | # and we need to decide where to insert -1 6 | if start == end: 7 | if arr[start] > val: 8 | return start 9 | else: 10 | return start+1 11 | 12 | # this occurs if we are moving beyond left's boundary 13 | # meaning the left boundary is the least position to 14 | # find a number greater than val 15 | if start > end: 16 | return start 17 | 18 | mid = (start+end)/2 19 | if arr[mid] < val: 20 | return binary_search(arr, val, mid+1, end) 21 | elif arr[mid] > val: 22 | return binary_search(arr, val, start, mid-1) 23 | else: 24 | return mid 25 | 26 | def insertion_sort(arr): 27 | for i in xrange(1, len(arr)): 28 | val = arr[i] 29 | j = binary_search(arr, val, 0, i-1) 30 | arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] 31 | return arr 32 | 33 | print("Sorted array:") 34 | print insertion_sort([37, 23, 0, 17, 12, 72, 31, 35 | 46, 100, 88, 54]) 36 | 37 | -------------------------------------------------------------------------------- /Python/BogoSort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def isSorted(arr) 4 | if len(arr) == 0 or len(arr) == 1 5 | return True 6 | for i in range(len(arr)-1) 7 | if(arr[i] arr[i+1]) 8 | return False 9 | return True 10 | 11 | def bogosort(arr) 12 | while not isSorted(arr) 13 | random.shuffle(arr) 14 | return arr -------------------------------------------------------------------------------- /Python/BubbleSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Bubble Sort 2 | 3 | def bubbleSort(arr): 4 | n = len(arr) 5 | 6 | # Traverse through all array elements 7 | for i in range(n): 8 | 9 | # Last i elements are already in place 10 | for j in range(0, n-i-1): 11 | 12 | # traverse the array from 0 to n-i-1 13 | # Swap if the element found is greater 14 | # than the next element 15 | if arr[j] > arr[j+1] : 16 | arr[j], arr[j+1] = arr[j+1], arr[j] 17 | 18 | # Driver code to test above 19 | arr = [64, 34, 25, 12, 22, 11, 90] 20 | 21 | bubbleSort(arr) 22 | 23 | print ("Sorted array is:") 24 | for i in range(len(arr)): 25 | print ("%d" %arr[i]), 26 | 27 | -------------------------------------------------------------------------------- /Python/BubbleSortRecursive.py: -------------------------------------------------------------------------------- 1 | # Python Program for implementation of Recursive Bubble sort 2 | 3 | def bubble_sort(number_list): 4 | for i, num in enumerate(number_list): 5 | try: 6 | if number_list[i+1] < num: 7 | number_list[i] = number_list[i+1] 8 | number_list[i+1] = num 9 | bubble_sort(number_list) 10 | except IndexError: 11 | pass 12 | return number_list 13 | 14 | # Driver code to test the code above 15 | number_list = [64, 34, 25, 12, 22, 11, 90] 16 | bubble_sort(number_list) 17 | 18 | print("Sorted array:"); 19 | for i in range(len(number_list)): 20 | print(number_list[i], end=' ') 21 | -------------------------------------------------------------------------------- /Python/BucketSort.py: -------------------------------------------------------------------------------- 1 | # Python3 program to sort an array 2 | # using bucket sort 3 | 4 | def insertionSort(b): 5 | for i in range(1, len(b)): 6 | up = b[i] 7 | j = i - 1 8 | while j >=0 and b[j] > up: 9 | b[j + 1] = b[j] 10 | j -= 1 11 | b[j + 1] = up 12 | return b 13 | 14 | def bucketSort(x): 15 | arr = [] 16 | slot_num = 10 # 10 means 10 slots, each 17 | # slot's size is 0.1 18 | for i in range(slot_num): 19 | arr.append([]) 20 | 21 | # Put array elements in different buckets 22 | for j in x: 23 | index_b = int(slot_num * j) 24 | arr[index_b].append(j) 25 | 26 | # Sort individual buckets 27 | for i in range(slot_num): 28 | arr[i] = insertionSort(arr[i]) 29 | 30 | # concatenate the result 31 | k = 0 32 | for i in range(slot_num): 33 | for j in range(len(arr[i])): 34 | x[k] = arr[i][j] 35 | k += 1 36 | return x 37 | 38 | # Driver Code 39 | x = [0.897, 0.565, 0.656, 40 | 0.1234, 0.665, 0.3434] 41 | print("Sorted Array is") 42 | print(bucketSort(x)) 43 | 44 | 45 | -------------------------------------------------------------------------------- /Python/CocktailSort.py: -------------------------------------------------------------------------------- 1 | def cocktailSort(a): 2 | n = len(a) 3 | swapped = True 4 | start = 0 5 | end = n-1 6 | while (swapped == True): 7 | 8 | # reset the swapped flag on entering the loop, 9 | # because it might be true from a previous 10 | # iteration. 11 | swapped = False 12 | 13 | # loop from left to right same as the bubble 14 | # sort 15 | for i in range (start, end): 16 | if (a[i] > a[i + 1]) : 17 | a[i], a[i + 1]= a[i + 1], a[i] 18 | swapped = True 19 | 20 | # if nothing moved, then array is sorted. 21 | if (swapped == False): 22 | break 23 | 24 | # otherwise, reset the swapped flag so that it 25 | # can be used in the next stage 26 | swapped = False 27 | 28 | # move the end point back by one, because 29 | # item at the end is in its rightful spot 30 | end = end-1 31 | 32 | # from right to left, doing the same 33 | # comparison as in the previous stage 34 | for i in range(end-1, start-1, -1): 35 | if (a[i] > a[i + 1]): 36 | a[i], a[i + 1] = a[i + 1], a[i] 37 | swapped = True 38 | 39 | # increase the starting point, because 40 | # the last stage would have moved the next 41 | # smallest number to its rightful spot. 42 | start = start + 1 43 | 44 | # Driver code to test above 45 | a = [5, 1, 4, 2, 8, 0, 2] 46 | cocktailSort(a) 47 | print("Sorted array is:") 48 | for i in range(len(a)): 49 | print ("% d" % a[i]), 50 | -------------------------------------------------------------------------------- /Python/CountingSort.py: -------------------------------------------------------------------------------- 1 | # Counting sort in Python programming 2 | 3 | 4 | def countingSort(array): 5 | size = len(array) 6 | output = [0] * size 7 | 8 | # Initialize count array 9 | count = [0] * 10 10 | 11 | # Store the count of each elements in count array 12 | for i in range(0, size): 13 | count[array[i]] += 1 14 | 15 | # Store the cummulative count 16 | for i in range(1, 10): 17 | count[i] += count[i - 1] 18 | 19 | # Find the index of each element of the original array in count array 20 | # place the elements in output array 21 | i = size - 1 22 | while i >= 0: 23 | output[count[array[i]] - 1] = array[i] 24 | count[array[i]] -= 1 25 | i -= 1 26 | 27 | # Copy the sorted elements into original array 28 | for i in range(0, size): 29 | array[i] = output[i] 30 | 31 | 32 | data = [4, 2, 2, 8, 3, 3, 1] 33 | countingSort(data) 34 | print("Sorted Array in Ascending Order: ") 35 | print(data) 36 | -------------------------------------------------------------------------------- /Python/CycleSort.py: -------------------------------------------------------------------------------- 1 | def cycleSort(array): 2 | writes = 0 3 | 4 | # Loop through the array to find cycles to rotate. 5 | for cycleStart in range(0, len(array) - 1): 6 | item = array[cycleStart] 7 | 8 | # Find where to put the item. 9 | pos = cycleStart 10 | for i in range(cycleStart + 1, len(array)): 11 | if array[i] < item: 12 | pos += 1 13 | 14 | # If the item is already there, this is not a cycle. 15 | if pos == cycleStart: 16 | continue 17 | 18 | # Otherwise, put the item there or right after any duplicates. 19 | while item == array[pos]: 20 | pos += 1 21 | array[pos], item = item, array[pos] 22 | writes += 1 23 | 24 | # Rotate the rest of the cycle. 25 | while pos != cycleStart: 26 | 27 | # Find where to put the item. 28 | pos = cycleStart 29 | for i in range(cycleStart + 1, len(array)): 30 | if array[i] < item: 31 | pos += 1 32 | 33 | # Put the item there or right after any duplicates. 34 | while item == array[pos]: 35 | pos += 1 36 | array[pos], item = item, array[pos] 37 | writes += 1 38 | 39 | return writes 40 | 41 | 42 | # driver code 43 | arr = [1, 8, 3, 9, 10, 10, 2, 4] 44 | n = len(arr) 45 | cycleSort(arr) 46 | 47 | print("After sort : ") 48 | for i in range(0, n): 49 | print(arr[i], end = ' ') -------------------------------------------------------------------------------- /Python/GnomeSort.py: -------------------------------------------------------------------------------- 1 | def swapPositions(list,posA, posB): 2 | list[posA], list[posB] = list[posB], list[posA] 3 | return list 4 | def gnomeSort(listToBeSorted): 5 | position = 0 6 | while position < len(listToBeSorted): 7 | if position == 0 or listToBeSorted[position] >= listToBeSorted[position - 1]: 8 | position = position +1 9 | else: 10 | swapPositions(listToBeSorted, position, position -1) 11 | position = position -1 12 | 13 | return listToBeSorted 14 | 15 | print ("Input numbers you want to sort, seperated by spaces.") 16 | inputList = [int(i) for i in input().split()] 17 | print ("List to be sorted: {0}".format(inputList)) 18 | gnomeSort(inputList) 19 | print ("The sorted list: {0}".format(inputList)) -------------------------------------------------------------------------------- /Python/InsertionSort.py: -------------------------------------------------------------------------------- 1 | def InsertionSort(List): 2 | for i in range(1, len(List)): 3 | key = List[i] 4 | j = i - 1 5 | while j >= 0 and key < List[j]: 6 | List[j + 1] = List[j] 7 | j -= 1 8 | List[j + 1] = key 9 | print('The sorted list: \t', List) 10 | 11 | if __name__ == "__main__": 12 | lst = [] 13 | size = int(input("\nEnter size of the list: \t")) 14 | for i in range(size): 15 | elements = int(input("Enter the element: \t")) 16 | lst.append(elements) 17 | InsertionSort(lst) -------------------------------------------------------------------------------- /Python/MergeSort.py: -------------------------------------------------------------------------------- 1 | def mergeSort(list): 2 | 3 | if len(list) > 1: 4 | midPointer = len(list) // 2 5 | left = list[:midPointer] 6 | right = list[midPointer:] 7 | 8 | mergeSort(left) 9 | mergeSort(right) 10 | 11 | i = 0 12 | j = 0 13 | k = 0 14 | 15 | while (i < len(left)) and (j < len(right)): 16 | if left[i] < right[j]: 17 | list[k] = left[i] 18 | i += 1 19 | else: 20 | list[k] = right[j] 21 | j += 1 22 | k += 1 23 | 24 | while i < len(left): 25 | list[k] = left[i] 26 | i += 1 27 | k += 1 28 | 29 | while j < len(right): 30 | list[k] = right[j] 31 | j += 1 32 | k += 1 33 | -------------------------------------------------------------------------------- /Python/QuickSort.py: -------------------------------------------------------------------------------- 1 | def partition(arr,low,high): 2 | i = ( low-1 ) 3 | pivot = arr[high] 4 | 5 | for j in range(low , high): 6 | if arr[j] <= pivot: 7 | i = i+1 8 | arr[i],arr[j] = arr[j],arr[i] 9 | 10 | arr[i+1],arr[high] = arr[high],arr[i+1] 11 | return (i+1) 12 | 13 | def quickSort(arr,low,high): 14 | if low < high: 15 | pi = partition(arr,low,high) 16 | 17 | quickSort(arr, low, pi-1) 18 | quickSort(arr, pi+1, high) 19 | 20 | if __name__ == "__main__": 21 | arr = [5, 3, 2, 5, 9, 1] 22 | quickSort(arr, 0, len(arr) - 1) 23 | print(arr) 24 | -------------------------------------------------------------------------------- /Python/RadixSort.py: -------------------------------------------------------------------------------- 1 | def radixSort(listToBeSorted): 2 | cyphers = 10 3 | maxLength = False 4 | placement = 1 5 | 6 | while not maxLength: 7 | maxLength = True 8 | 9 | buckets = [list() for _ in range(cyphers)] 10 | for i in listToBeSorted: 11 | tmp = i // placement 12 | buckets[tmp % cyphers].append(i) 13 | if maxLength and tmp > 0: 14 | maxLength = False 15 | element = 0 16 | for cipher in range(cyphers): 17 | bucket = buckets[cipher] 18 | for buck in bucket: 19 | listToBeSorted[element] = buck 20 | element += 1 21 | 22 | placement *= cyphers 23 | 24 | 25 | print ("Input integers you want to sort, seperated by spaces.") 26 | 27 | inputList = [int(i) for i in input().split()] 28 | 29 | print ("List to be sorted: {0}".format(inputList)) 30 | 31 | radixSort(inputList) 32 | 33 | print ("The sorted list: {0}".format(inputList)) 34 | -------------------------------------------------------------------------------- /Python/SelectionSort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(l): 2 | for start in range(len(l)): 3 | 4 | #assign start value as minimum value 5 | minpos=start 6 | 7 | for i in range(start,len(l)): 8 | if(l[i] temp and j >= left: 13 | 14 | arr[j+1] = arr[j] 15 | j -= 1 16 | 17 | arr[j+1] = temp 18 | 19 | # merge function merges the sorted runs 20 | def merge(arr, l, m, r): 21 | 22 | # original array is broken in two parts 23 | # left and right array 24 | len1, len2 = m - l + 1, r - m 25 | left, right = [], [] 26 | for i in range(0, len1): 27 | left.append(arr[l + i]) 28 | for i in range(0, len2): 29 | right.append(arr[m + 1 + i]) 30 | 31 | i, j, k = 0, 0, l 32 | # after comparing, we merge those two array 33 | # in larger sub array 34 | while i < len1 and j < len2: 35 | 36 | if left[i] <= right[j]: 37 | arr[k] = left[i] 38 | i += 1 39 | 40 | else: 41 | arr[k] = right[j] 42 | j += 1 43 | 44 | k += 1 45 | 46 | # copy remaining elements of left, if any 47 | while i < len1: 48 | 49 | arr[k] = left[i] 50 | k += 1 51 | i += 1 52 | 53 | # copy remaining element of right, if any 54 | while j < len2: 55 | arr[k] = right[j] 56 | k += 1 57 | j += 1 58 | 59 | # iterative Timsort function to sort the 60 | # array[0...n-1] (similar to merge sort) 61 | def timSort(arr, n): 62 | 63 | # Sort individual subarrays of size RUN 64 | for i in range(0, n, RUN): 65 | insertionSort(arr, i, min((i+31), (n-1))) 66 | 67 | # start merging from size RUN (or 32). It will merge 68 | # to form size 64, then 128, 256 and so on .... 69 | size = RUN 70 | while size < n: 71 | 72 | # pick starting point of left sub array. We 73 | # are going to merge arr[left..left+size-1] 74 | # and arr[left+size, left+2*size-1] 75 | # After every merge, we increase left by 2*size 76 | for left in range(0, n, 2*size): 77 | 78 | # find ending point of left sub array 79 | # mid+1 is starting point of right sub array 80 | mid = left + size - 1 81 | right = min((left + 2*size - 1), (n-1)) 82 | 83 | # merge sub array arr[left.....mid] & 84 | # arr[mid+1....right] 85 | merge(arr, left, mid, right) 86 | 87 | size = 2*size 88 | 89 | # utility function to print the Array 90 | def printArray(arr, n): 91 | 92 | for i in range(0, n): 93 | print(arr[i], end = " ") 94 | print() 95 | 96 | 97 | # Driver program to test above function 98 | if __name__ == "__main__": 99 | 100 | arr = [5, 21, 7, 23, 19] 101 | n = len(arr) 102 | print("Given Array is") 103 | printArray(arr, n) 104 | 105 | timSort(arr, n) 106 | 107 | print("After Sorting Array is") 108 | printArray(arr, n) 109 | -------------------------------------------------------------------------------- /Python/heapSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of heap Sort 2 | 3 | # To heapify subtree rooted at index i. 4 | # n is size of heap 5 | def heapify(arr, n, i): 6 | largest = i # Initialize largest as root 7 | l = 2 * i + 1 # left = 2*i + 1 8 | r = 2 * i + 2 # right = 2*i + 2 9 | 10 | # See if left child of root exists and is 11 | # greater than root 12 | if l < n and arr[i] < arr[l]: 13 | largest = l 14 | 15 | # See if right child of root exists and is 16 | # greater than root 17 | if r < n and arr[largest] < arr[r]: 18 | largest = r 19 | 20 | # Change root, if needed 21 | if largest != i: 22 | arr[i],arr[largest] = arr[largest],arr[i] # swap 23 | 24 | # Heapify the root. 25 | heapify(arr, n, largest) 26 | 27 | # The main function to sort an array of given size 28 | def heapSort(arr): 29 | n = len(arr) 30 | 31 | # Build a maxheap. 32 | for i in range(n, -1, -1): 33 | heapify(arr, n, i) 34 | 35 | # One by one extract elements 36 | for i in range(n-1, 0, -1): 37 | arr[i], arr[0] = arr[0], arr[i] # swap 38 | heapify(arr, i, 0) 39 | 40 | # Driver code to test above 41 | arr = [ 12, 11, 13, 5, 6, 7] 42 | heapSort(arr) 43 | n = len(arr) 44 | print ("Sorted array is") 45 | for i in range(n): 46 | print ("%d" %arr[i]), 47 | -------------------------------------------------------------------------------- /Python/speed_of_sorting_python.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/argonautica/sorting-algorithms/b9ebd2aadc6b59e5feba7d1fe9e0c6a036d33dba/Python/speed_of_sorting_python.PNG -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | 4 | 5 | Stars 6 | GitHub issues 7 | GitHub issues 8 |

9 | 10 | 11 | # Sorting Algorithms 12 | Sorting algorithms implemented in different languages (for hacktoberfest). This repository is open to everyone. Feel free to add any sorting algorithms. The instructions for how to contribute to this repo are down below. 13 | 14 | 15 | ## List of Algorithms ⌨️ 16 | | Language | Algorithms | 17 | |----------|------------| 18 | | Assembly | [`Bubble Sort`](Assembly/bubblesort.asm) [`Quick Sort`](Assembly/quicksort.asm) 19 | | C++ | [`Interchange Sort`](C++/InterchangeSort.cpp ) [`Bubble Sort`](C++/BubbleSort.cpp) [`Heap Sort`](C++/HeapSort.cpp)
[`Insertion Sort`](C++/InsertionSort.cpp) [`Merge Sort`](C++/MergeSort.cpp) [`Quick Sort`](C++/QuickSort.cpp)
[`Selection Sort`](C++/SelectionSort.cpp) [`Shell Sort`](C++/ShellSort.cpp) [`Binary Insertion Sort`](C++/BinaryInsertionSort.cpp)
[`Bucket Sort`](C++/BucketSort.cpp) [`Cycle Sort`](C++/cycleSort.cpp) [`K Way Merge Sort`](C++/)
[`Radix Sort`](C++/RadixSort.cpp) [`Tree Sort`](C++/treeSort.cpp) [`PigeonholeSort`](C++/PigeonholeSort.cpp) | 20 | | C | [`Bubble Sort`](C/BubbleSort.c) [`Insertion Sort`](C/InsertionSort.c) [`Merge Sort`](C/MergeSort.c)
[`Quick Sort`](C/QuickSort.c) [`Selection Sort`](C/SelectionSort.c) [`Bubble Sort #2`](C/Bubble-Sort.c)
[`Gnome Sort`](C/gnomesort.c) [`Heap Sort`](C/heapsort.c) [`Radix Sort`](C/radixsort.c)
[`Tree Sort`](C/treesort.c) | 21 | | C# | [`Bubble Sort`](C#/BubbleSort.cs) [`Binary Insertion Sort`](C#/BinaryInsertionSort.cs) [`Heap Sort`](C#/HeapSort.cs)
[`Insertion Sort`](C#/InsertionSort.cs) [`Merge Sort`](C#/MergeSort.cs) [`Quick Sort`](C#/QuickSort.cs)
[`Selection Sort`](C#/SelectionSort.cs) [`Shell Sort`](C#/ShellSort.cs) | 22 | | Go | [`Radix Sort`](Go/RadixSort.go) [`Bubble Sort`](Go/BubbleSort.go) [`Insertion Sort`](Go/InsertionSort.go) [`Counting Sort`](Go/CountingSort.go)| 23 | | Java | [`Bead Sort`](Java/BeadSort.java) [`Bogo Sort`](Java/BogoSort.java) [`Bubble Sort`](Java/BubbleSort.java)
[`Counting Sort`](Java/Counting%20Sort.java) [`Heap Sort`](Java/HeapSort.java) [`Insertion Sort`](Java/InsertionSort.java)
[`Merge Sort`](Java/MergeSort.java) [`Quick Sort`](Java/QuickSort.java) [`Radix Sort`](Java/RadixSort.java)
[`Selection Sort`](Java/SelectionSort.java) [`Shell Sort`](Java/ShellSort.java) [`Tim Sort`](Java/TimSort.java)
[`Comb Sort`](Java/CombSort.java) [`Binary Insertion Sort`](Java/BinaryInsertionSort.java) [`Gnome Sort`](Java/GnomeSort.java) [`Topological Sort`](Java/TopologicalSort.java)| 24 | | Javascript | [`Bogo Sort`](Javascript/bogoSort.js) [`Counting Sort`](Javascript/countingSort.js) [`Heap Sort`](Javascript/HeapSort.js) [`Insertion Sort`](Javascript/Insertionsort.js) [`Merge Sort`](Javascript/MergeSort.js)
[`Quick Sort`](Javascript/Quicksort.js) [`Bubble Sort`](Javascript/bubbleSort.js) [`Shell Sort`](Javascript/shellSort.js ) [`Selection Sort`](Javascript/selectionSort.js)
[`Radix Sort`](Javascript/RadixSort.js) | 25 | | Lua | [`Quick Sort`](Lua/quicksort.lua) | 26 | | Python | [`Bogo Sort`](Python/BogoSort.py) [`Bubble Sort`](Python/BubbleSort.py) [`Bucket Sort`](Python/BucketSort.py) [`Bubble Sort Recursive`](Python/BubbleSortRecursive.py)
[`Gnome Sort`](Python/GnomeSort.py) [`Insertion Sort`](Python/InsertionSort.py) [`Merge Sort`](Python/MergeSort.py)
[`Quick Sort`](Python/QuickSort.py) [`Radix Sort`](Python/RadixSort.py) [`Selection Sort`](Python/SelectionSort.py)
[`Binary Insertion Sort`](Python/BinaryInsertionSort.py) [`Heap Sort`](Python/heapSort.py) | 27 | | Ruby | [`Bubble Sort`](Ruby/bubble_sort.rb) [`Gnome Sort`](Ruby/gnome_sort.rb) [`Quick sort`](Ruby/quick_sort.rb) [`Selection sort`](Ruby/selection_sort.rb) [`Sort`](Ruby/sort.rb) [`Reverse sort`](Ruby/reverse.rb) 28 | | Rust | [`Bubble Sort`](Rust/Bubble_Sort.rs) 29 | | Kotlin |[`Merge Sort`](Kotlin/MergeSort.kt) [`Bubble Sort`](Kotlin/BubbleSort.kt) [`Selection Sort`](Kotlin/selectionSort.kt)
[`Heap Sort`](Kotlin/HeapSort.kt) [`Insertion Sort`](Kotlin/InsertionSort.kt) [`Quick Sort`](Kotlin/QuickSort.kt) [`Bogo Sort`](Kotlin/BogoSort.kt)[`Counting Sort`](Kotlin/CountingSort.kt) [`Radix Sort`](Kotlin/RadixSort.kt) [`Cocktail Shaker Sort`](Kotlin/CocktailShakerSort.kt) 30 | | Elixir | [`Selection Sort`](Elixir/selectionSort.exs) 31 | 32 | 33 | 34 | ## Contributing 🖇️ 35 | If there's an existing folder named with your chosen language, create a file for your new algorithm inside, calling it by the algorithm name and use the appropriate file extension i.e. `bubbleSort.js`. If there aren't any algorithms in your choice of language, feel free to start your own folder and place your implementations inside, and don't forget to update the [README.md](README.md)! 36 | 37 | -------------------------------------------------------------------------------- /Ruby/bubble_sort.rb: -------------------------------------------------------------------------------- 1 | def bubble_sort(arr) 2 | length = arr.length - 1 3 | 4 | (0..length).each do |i| 5 | (0..length - i - 1).each do |j| 6 | next_i = j + 1 7 | arr[next_i], arr[j] = arr[j], arr[next_i] if arr[j] > arr[next_i] 8 | end 9 | end 10 | 11 | arr 12 | end 13 | -------------------------------------------------------------------------------- /Ruby/gnome_sort.rb: -------------------------------------------------------------------------------- 1 | def gnome_sort(arr) 2 | pos = 0 3 | while pos < arr.count 4 | if pos.zero? || arr[pos] >= arr[pos - 1] 5 | pos += 1 6 | else 7 | arr[pos], arr[pos - 1] = arr[pos - 1], arr[pos] 8 | pos -= 1 9 | end 10 | end 11 | arr 12 | end 13 | -------------------------------------------------------------------------------- /Ruby/quick_sort.rb: -------------------------------------------------------------------------------- 1 | def quicksort(arr, left = 0, right = nil) 2 | right = arr.length - 1 if right.nil? 3 | 4 | if left < right 5 | pivot = right 6 | 7 | partition_index = partition(arr, pivot, left, right) 8 | 9 | quicksort(arr, left, partition_index - 1) 10 | quicksort(arr, partition_index + 1, right) 11 | end 12 | arr 13 | end 14 | 15 | def partition(arr, pivot, left, right) 16 | pivot_value = arr[pivot] 17 | index = left 18 | 19 | (left..right).each do |i| 20 | if arr[i] < pivot_value 21 | arr[i], arr[index] = arr[index], arr[i] 22 | index += 1 23 | end 24 | end 25 | arr[right], arr[index] = arr[index], arr[right] 26 | index 27 | end 28 | -------------------------------------------------------------------------------- /Ruby/reverse.rb: -------------------------------------------------------------------------------- 1 | letters = ["b", "d", "e", "a", "c"] 2 | => ["b", "d", "e", "a", "c"] 3 | # Ruby doesn't care about the alphabetical pattern, it only reverses the order of the array 4 | letters.reverse 5 | => ["c", "a", "e", "d", "b"] 6 | # The original array wasn't mutated because bang(!) wasn't used. 7 | letters 8 | => ["b", "d", "e", "a", "c"] 9 | 10 | # Using bang(!) here mutates the array so the order has changes 11 | letters.reverse! 12 | => ["c", "a", "e", "d", "b"] 13 | letters 14 | => ["c", "a", "e", "d", "b"] -------------------------------------------------------------------------------- /Ruby/selection_sort.rb: -------------------------------------------------------------------------------- 1 | def selection_sort(arr) 2 | n = arr.length 3 | (0...n).each do |i| 4 | ((i + 1)...n).each do |j| 5 | arr[j], arr[i] = arr[i], arr[j] if arr[j] < arr[i] 6 | end 7 | end 8 | arr 9 | end -------------------------------------------------------------------------------- /Ruby/sort.rb: -------------------------------------------------------------------------------- 1 | letters = [b, d, e, a, c] 2 | letters.sort 3 | => ["a", "b", "c", "d", "e"] 4 | 5 | # checking letters again shows the original array 6 | letters 7 | => ["b", "d", "e", "a", "c"] 8 | 9 | letters.sort! 10 | => ["a", "b", "c", "d", "e"] 11 | letters 12 | => ["a", "b", "c", "d", "e"] 13 | 14 | # using .sort! (with the exclamation mark) mutates your original letters array. -------------------------------------------------------------------------------- /Rust/Bubble_Sort.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | 3 | let mut num_array = [200, 31, 80, 14, 1, 432, 84, 33, 18]; 4 | 5 | let mut swap_performed = true; 6 | 7 | while swap_performed{ 8 | swap_performed = false; 9 | 10 | for i in 1..num_array.len() { 11 | if num_array[i-1]> num_array[i] { 12 | num_array.swap(i-1, i); 13 | swap_performed=true 14 | } 15 | } 16 | } 17 | 18 | println!("{}", "Sorted Array:"); 19 | println!("{:?}", num_array); 20 | } -------------------------------------------------------------------------------- /lua/quicksort.lua: -------------------------------------------------------------------------------- 1 | function partition(array, left, right, pivotIndex) 2 | local pivotValue = array[pivotIndex] 3 | array[pivotIndex], array[right] = array[right], array[pivotIndex] 4 | 5 | local storeIndex = left 6 | 7 | for i = left, right-1 do 8 | if array[i] <= pivotValue then 9 | array[i], array[storeIndex] = array[storeIndex], array[i] 10 | storeIndex = storeIndex + 1 11 | end 12 | array[storeIndex], array[right] = array[right], array[storeIndex] 13 | end 14 | 15 | return storeIndex 16 | end 17 | 18 | function quicksort(array, left, right) 19 | if right > left then 20 | local pivotNewIndex = partition(array, left, right, left) 21 | quicksort(array, left, pivotNewIndex - 1) 22 | quicksort(array, pivotNewIndex + 1, right) 23 | end 24 | end 25 | --------------------------------------------------------------------------------