Problem
Bubble sort and Shell sort
Solution
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
void print_list(int list[], int len)
{
for(int i = 0; i < len; i++){
cout << list[i] << " ";
}
cout << endl;
}
void bubble_sort(int list[], int len)
{
int i, j;
bool swapped;
for(i = 0; i < len - 1; i++){
swapped = false;
for(j = 0; j < len -1 - i; j++){
if(list[j] > list[j + 1]){
int t = list[j + 1];
list[j + 1] = list[j];
list[j] = t;
swapped = true;
}
}
if(!swapped){
break;
}
}
}
void shell_sort(int list[], int len)
{
int d = len;
while(d > 1){
d = (d + 1) / 2;
for(int i = 0; i < len - d; i ++ ){
if(list[i] > list[i + d]){
int t = list[i + d];
list[i + d] = list[i];
list[i] = t;
}
}
}
}
int main(int argc, char* argv[])
{
int i, j, n;
int list[100] = {9, 3, 2, 7, 5, 4, 6, 1, 8, 0};
srand((unsigned)time(NULL));
cout << "before sort " << endl;
for(i = 0; i < 10; i ++){
n = rand()%100;
list[i] = n;
}
print_list(list, 10);
//bubble_sort(list, 10);
shell_sort(list, 10);
cout << "after shell sort " << endl;
print_list(list, 10);
return 0;
}