Code:
#include iostream
using namespace std;
// A function to swap values using call by reference.
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
// A function implementing shaker sort.
void ShakerSort(int a[], int n)
{
int i, j, k;
for(i = 0; i < n;)
{
// First phase for ascending highest value to the highest unsorted index.
for(j = i+1; j < n; j++)
{
if(a[j] < a[j-1])
swap(&a[j], &a[j-1]);
}
// Decrementing highest index.
n--;
// Second phase for descending lowest value to the lowest unsorted index.
for(k = n-1; k > i; k--)
{
if(a[k] < a[k-1])
swap(&a[k], &a[k-1]);
}
// Incrementing lowest index.
i++;
}
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<
cin>>arr[i];
}
ShakerSort(arr, n);
// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<
return 0;
}
Output:
Case 1:(average case)
Enter the number of data element to be sorted: 5
Enter element 1: 998
Enter element 2: 451
Enter element 3: 2
Enter element 4: 35
Enter element 5: 1206
Sorted Data ->2->35->451->998->1206
Case 2:(best case)
Enter the number of data element to be sorted: 5
Enter element 1: 2
Enter element 2: 332
Enter element 3: 456
Enter element 4: 1024
Enter element 5: 16565
Sorted Data ->2->332->456->1024->16565
case 3: (worst case)
Enter the number of data element to be sorted: 5
Enter element 1: 99845
Enter element 2: 564
Enter element 3: 332
Enter element 4: 86
Enter element 5: 1
Sorted Data ->1->86->332->564->99845
More C++ Programs: