Sunday, May 9, 2021

Shuttle Sort using C

 In Shuttle Sort technique for n elements in an array a, it requires n-1 passes. When i-th pass(1<=i<=n) begins, the first i elements, i.e., elements a[0] to a[i-1] have been sorted and these occupy the first i positions of the array. To insert (i+1)th element, a[i] is compared with a[i-1] and if the value of a[i] is smaller than a[i-1] then they are exchanged. In the same way the process continues until either no exchange is required or the beginning of the array is reached.

Shuttle Sort using C


Time complexity of the algorithm is O(n^2).


The complete source code is given below

/* 
 * File:   ShuttleSort.c
 */

#include <stdio.h>
#include <stdlib.h>

void shuttleSort(int a[], int n) {
    int i = 1, j;
    int temp;
    while (i < n) {
        j = i - 1;
        while (j >= 0) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
                j--;
            } else {
                break;
            }
        }
        i++;
    }
    printf("\n");
    printf("\nThe sorted array elements are given below\n");
    for (i = 0; i < n; i++) {
        printf("a[%d]=%d ", i, a[i]);
    }
}

int main() {
    int i, n = 6;
    int a[] = {15, 8, 17, 12, 38, 19};
    printf("\n:: Shuttle Sort ::\n");
    printf("\nInput array elements\n");
    for (i = 0; i < n; i++) {
        printf("a[%d]=%d ", i, a[i]);
    }
    shuttleSort(a, n);
}

Output

:: Shuttle Sort ::

Input array elements
a[0]=15 a[1]=8 a[2]=17 a[3]=12 a[4]=38 a[5]=19 

The sorted array elements are given below
a[0]=8 a[1]=12 a[2]=15 a[3]=17 a[4]=19 a[5]=38




No comments:

Post a Comment