Hmm, I thought bubblesort were something like this:
Both are bubble sorts. These are the simple sorting algorithms
Code:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void bubble_sort1(int A[], int n)
{
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
if (A[i] > A[j]) {
int t = A[i];
A[i] = A[j];
A[j] = t;
}
}
}
}
void bubble_sort2(int A[], int n)
{
bool noswap = false;
int i = 0;
while(!noswap) {
noswap = true;
for (int j = i + 1; j < n; ++j) {
if (A[i] > A[j]) {
int t = A[i];
A[i] = A[j];
A[j] = t;
noswap = false;
}
}
i++;
}
}
void selection_sort(int A[], int n)
{
int k;
for (int i = 0; i < n - 1; ++i) {
k = i;
for (int j = i + 1; j < n; ++j) {
if (A[j] < A[k])
k = j;
}
int t = A[i];
A[i] = A[k];
A[k] = t;
}
}
void insertion_sort(int A[], int n)
{
for (int i = 1; i < n; ++i) {
int k = A[i];
int j = i - 1;
while(j >= 0 && k < A[j]) {
A[j + 1] = A[j];
j--;
}
A[j + 1] = k;
}
}
void randomize_array(int A[], int n)
{
for (int i = 0; i < n; ++i) {
A[i] = rand() % 100;
}
}
void print_array(int A[], int n)
{
for (int i = 0; i < n; ++i) {
cout << A[i] << " ";
if ((i + 1) % 15 == 0 && i < n - 1)
cout << endl;
}
cout << endl;
}
int main(void)
{
const int N = 100;
int A[N];
srand(time(0));
randomize_array(A, N);
bubble_sort1(A, N);
cout << "bubble_sort1" << endl;
print_array(A, N);
cout << endl;
randomize_array(A, N);
bubble_sort2(A, N);
cout << "bubble_sort2" << endl;
print_array(A, N);
cout << endl;
randomize_array(A, N);
selection_sort(A, N);
cout << "selection sort" << endl;
print_array(A, N);
cout << endl;
randomize_array(A, N);
insertion_sort(A, N);
print_array(A, N);
return 0;
}