Skip to content

Instantly share code, notes, and snippets.

@kaiimran
Created June 4, 2020 17:11
Show Gist options
  • Save kaiimran/07e77dface24b58f8142e6a09d3f20e2 to your computer and use it in GitHub Desktop.
Save kaiimran/07e77dface24b58f8142e6a09d3f20e2 to your computer and use it in GitHub Desktop.
Sort the numbers stored in $data variable. $data = [9,7,5,3,0];
#include<iostream>
#include<conio.h>
#include<cstring>
using namespace std;
void display(int[], int);
void sort(int[], int);
void sort2(int[], int);
void sort3(int[], int);
int main()
{
const int N = 5;
int data[N] = {9,7,5,3,0};
//can only choose 1 function to call, please comment the other 2 if wanna try a function
sort(data, N);
//sort2(data, N);
//sort3(data, N);
_getch();
return 0;
}
void sort(int data[], int N)
{
int temp, swaps;
for(int j=0; j<N-1; j++)
{
swaps = 0;
for(int i=0; i<N-1; i++)
{
if(data[i] > data[i+1])
{
temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
swaps=1;
}
display(data, N);
}
cout<<endl;
if(!swaps)
{
break;
}
}
}
void sort2(int data[], int N)
{
int temp, swaps;
for(int j=0; j<N; j++)
{
swaps = 0;
for(int i=0; i<N-1; i++)
{
if(data[i] > data[i+1])
{
temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
swaps=1;
}
if(swaps)
display(data, N);
}
cout<<endl;
if(!swaps)
{
break;
}
}
}
//Fastest
void sort3(int data[], int N)
{
int temp, swaps;
for(int j=0; j<N-1; j++)
{
swaps = 0;
for(int i=0; i<N-j-1; i++)
{
if(data[i] > data[i+1])
{
temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
swaps = 1;
}
display(data, N);
}
if(!swaps)
{
break;
}
}
}
void display(int data[], int N)
{
for(int x=0; x<N; x++)
{
cout<<data[x]<<" ";
}
cout<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment