HOME

Project Task: Three — C++ shell sort

Introduction

add something here

Source Code: C++

add something here

//
// C++ implementation of Shell Sort
//
// $Id: shellsort.cc,v 0.2 2023/03/11 14:28:10 kc4zvw Exp kc4zvw $
//

#include <iostream>

using namespace std;

/* function prototypes */

void printArray(int [], int);
int shellSort(int [], int);

int main()
{
    int arr[] = {12, 34, 54, 2, 3, 45, 11, 10, 5, 67, 84}, i;
    int n = sizeof(arr)/sizeof(arr[0]);

    cout << "Sample program to sort a list of integers in an array\n" << endl;

    cout << "Array before sorting: " << endl;
    printArray(arr, n);

    shellSort(arr, n);

    cout << "\nArray after sorting: " << endl;
    printArray(arr, n);

    cout << endl;

    return 0;
}

/* Function to sort arr using shellSort */

int shellSort(int arr[], int n)
{
    // Start with a big gap, then reduce the gap
    for (int gap = n/2; gap > 0; gap /= 2) {
        // Do a gapped insertion sort for this gap size.
        // The first gap elements a[0..gap-1] are already in gapped order
        // keep adding one more element until the entire array is
        // gap sorted
        for (int i = gap; i < n; i += 1) {
            // add a[i] to the elements that have been gap sorted
            // save a[i] in temp and make a hole at position i
            int temp = arr[i];

            // shift earlier gap-sorted elements up until the correct
            // location for a[i] is found
            int j;
            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
                arr[j] = arr[j - gap];

            // put temp (the original a[i]) in its correct location
            arr[j] = temp;
        }
    }
    return 0;
}

void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

/* End of File */

  

Operation Notes

add something here


kc4zvw@www:~$ ./shellsort3
Sample program to sort a list of integers in an array

Array before sorting:
12 34 54 2 3 45 11 10 5 67 84

Array after sorting:
2 3 5 10 11 12 34 45 54 67 84

kc4zvw@www:~$

  

References

add something here

  1. Links ...
  2. Links ...
  3. Links ...
  4. Links ...
  5. Links ...



Copyright © 2023 by David Billsbrough (KC4ZVW)


Revised: Saturday, March 11, 2023 at 09:20:19 AM (EST)