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 |
6 |
7 |
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 |
--------------------------------------------------------------------------------