Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Monday, May 13, 2019

Bubble Sort

Pseudocode:


for j = 0 to n -2 // no need till n-2 as it will validate already properly aligned values(see code)
    if a[j] > a[j+1]
        swap (a[j], a[j+1])
 After the above pass, the largest element will come at the end.

Perform the above pass for each of the elements in the array.

Code
#include <stdio.h>

#define NELEMS(x) (sizeof (x) / sizeof (x[0]))

void display(int arr[], int n)
{
    int i;
    for (i = 0; i < n; ++i)
        printf("%d ", arr[i]);

    printf("\n");
}

void swap(int *x, int *y)
{
    int t = *x;
    *x = *y;
    *y = t;
}

void bubble(int arr[], int n)
{
    int i, j;
    int swapped = 0;
    for (i = 0; i < n - 1; ++i) { // no need of <n as bigger will find its way anyway
        swapped = 0;
        for (j = 0; j < n - i - 1; ++j) { // j < n-2 also works, but this is not needed
            if (arr[j] > arr[j + 1]) {
                swap(arr + j, arr + j + 1);
                swapped = 1;
                display(arr, 8);
            }
        }
        if (swapped == 0) break; // if no swap happened, no need to continue any further
    }
}

int main()
{
    int arr[] = { 17, 21, 19, 15, 5, 99, 1, 0 };
    /* int arr[] = { 17, 21, 19, 98, 99, 100, 101, 102 }; // almost sorted (usage of swapped flag helps here) */

    printf("Unsorted: ");
    display(arr, NELEMS(arr));

    bubble(arr, NELEMS(arr));

    printf("Sorted: ");
    display(arr, NELEMS(arr));
}

Output:
Unsorted: 17 21 19 15 5 99 1 0
17 19 21 15 5 99 1 0
17 19 15 21 5 99 1 0
17 19 15 5 21 99 1 0
17 19 15 5 21 1 99 0
17 19 15 5 21 1 0 99
17 15 19 5 21 1 0 99
17 15 5 19 21 1 0 99
17 15 5 19 1 21 0 99
17 15 5 19 1 0 21 99
15 17 5 19 1 0 21 99
15 5 17 19 1 0 21 99
15 5 17 1 19 0 21 99
15 5 17 1 0 19 21 99
5 15 17 1 0 19 21 99
5 15 1 17 0 19 21 99
5 15 1 0 17 19 21 99
5 1 15 0 17 19 21 99
5 1 0 15 17 19 21 99
1 5 0 15 17 19 21 99
1 0 5 15 17 19 21 99
0 1 5 15 17 19 21 99
Sorted: 0 1 5 15 17 19 21 99

Time Complexity: O(n^n)

Selection Sort


Pseudocode:
  • Take element in 0th position
  • From 1st to (n-1)th position, find the smallest element and its index.
  • If we found a smallest element, swap it with 0th position
  • Repeat the above for all the positions
  • NOTE: Selection sort basically means, fill the position of each index (starting from 0) by it's appropriate value (by choosing the minimum amount in the remaining indexes in each loop)
Psuedocode flow:
SelectionSort (A, n)
{
    for i = 0 to n -1 // we can do it till n-2, as n-1 will automatically have biggest element in its position
    {
        iMin = i
        for j = i+1 to n-1
         {
            if (A[j] < A[iMin])
                iMin = j
           }
            swap (A[iMin], A[i])
    }
}

C Code:

#include <stdio.h>

#define NELEMS(x) (sizeof (x)/sizeof(x[0]))

void swap(int *x, int *y)
{
    int t = *x;
    *x = *y;
    *y = t;
}

void display(int arr[], int size)
{
    int i;
    for (i = 0; i < size; ++i) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

void selection(int arr[], int n)
{
    int i, j, iMin;

    for (i = 0; i < n - 1; ++i) { // no need for last iteration, as the biggest number will be there anyways (due to previous operation)
        iMin = i; // find the right element for this position
        for (j = i + 1; j < n; ++j) {
            if (arr[j] < arr[iMin]) {
                iMin = j;
            }
        }
        swap(arr + iMin, arr + i);
        display(arr, 7); // NELEMS wont' work as it will be converted as pointer _here_
    }
}

int main()
{
    int arr[] = { 21, 5, 22, 74, 0, 99, 18 };

    printf("UnSorted: ");
    display(arr, NELEMS(arr));

    selection(arr, NELEMS(arr));

    printf("Sorted: ");
    display(arr, NELEMS(arr));
    return (0);

}


Output:
UnSorted: 21 5 22 74 0 99 18
0 5 22 74 21 99 18
0 5 22 74 21 99 18
0 5 18 74 21 99 22
0 5 18 21 74 99 22
0 5 18 21 22 99 74
0 5 18 21 22 74 99
Sorted: 0 5 18 21 22 74 99
[NOTE that, each index starting from 0 (referred by iMin), will pull the appropriate value, by going through the loop]

Sorting Basics

Sorting


Sorting is basically essential to do the searching.

Linear Search:
If we are to search a data in an unsorted pool of data, we call the search as Linear Search.
If the number of data in the pool is 'n', and we are to search for a data 'd', then we need to compare 'd' against (n-1) elements.
If n is 2^64, and if each comparison takes 1 ms, then we will need 2^64 ms (worst-case) to find the data.

size = n
n = 2^64 => 2^64 comparisons

Sorted:
If we the pool is sorted, then we can use Binary search.
size = n
And if n = 2^64 => 64 ms

Number of Sorting algorithms:

  1. Selection Sort
  2. Bubble Sort
  3. Insertion Sort
  4. Merge Sort
  5. Quick Sort
  6. Heap Sort
  7. Counting Sort
  8. Radix Sort
  9. [And many more]
Classification of these algorithms is based on:
  1. Time Complexity (Big O Notation)
  2. Space Complexity or Memory Usage [Merge sort, uses temporary storage]
  3. Stability (already sorted items in the input, will be preserved in the sorted list). For ex, cards of 6heart and 6clubs along with other cards, will remain in same order even in sorted list
  4. Internal (RAM) or External Sort (data in Disc or tapes)
  5. Recursive (Quick and Merge) and Non-Recursive