// Shell Sort // I want to use three different types of loops here #include <ios
ID: 3737098 • Letter: #
Question
// Shell Sort
// I want to use three different types of loops here
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
// Functions prototype
int myRand();
void sortArray(int shellSort[], int number);
void displayArray(int shellSort[]);
int main()
{
int myArray[30];
srand((unsigned)time(NULL));
for(int i = 0; i < 20; i++)
{
myArray[i] = myRand();
}
sortArray(myArray, 20); // Calling function sortArray
displayArray(myArray); // Calling function displayArray
return 0;
}
int myRand()
{
return(1 + rand() % 50); // return random number from 1 to 50
}
void sortArray(int shellSort[], int number)
{
int temp;
for(int x = 0; x < number; x++)
{
for(int j = 0; j < number; j++)
{
if(shellSort[j] > shellSort[j + 1])
{
temp = shellSort[j];
shellSort[j] = shellSort[j + 1];
shellSort[j + 1] = temp;
}
}
}
}
void displayArray(int shellSort[])
{
for(int y = 0; y < 20; y++)
{
cout << shellSort[y];
cout << endl;
}
}
Explanation / Answer
Hi Student,
I have written the code of shell sort using all the three loops.
1. Using For Loop
void sortArrayUsingForLoop(int shellSort[], int number)
{
int temp;
for(int x = 0; x < number; x++)
{
for(int j = 0; j < number; j++)
{
if(shellSort[j] > shellSort[j + 1])
{
temp = shellSort[j];
shellSort[j] = shellSort[j + 1];
shellSort[j + 1] = temp;
}
}
}
}
2. Using while loop
void sortArrayUsingWhileLoop(int shellSort[], int number)
{
int temp;
int x=0,j=0;
while(x < number){
j=0;
while(j<number){
if(shellSort[j] > shellSort[j + 1])
{
temp = shellSort[j];
shellSort[j] = shellSort[j + 1];
shellSort[j + 1] = temp;
}
j++;
}
x++;
}
}
3. Using Do while Loop
void sortArrayUsingDoWhileLoop(int shellSort[], int number)
{
int temp;
int x=0,j=0;
do{
j=0;
do{
if(shellSort[j] > shellSort[j + 1])
{
temp = shellSort[j];
shellSort[j] = shellSort[j + 1];
shellSort[j + 1] = temp;
}
j++;
}while(j<number);
x++;
}while(x<number);
}
Happy Learning :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.