# Sorting Algorithms

· · Code Snippet
Save
828 Views
```This code uses a variety of sorting methods. This code compiles with Borland C++ 5.0 it's useful for seeing how to duplicate the algorithms in other languages. Each sort is found in a separate function called in the main function. This version uses a vector and can sort up to 5 million numbers(possibly more). I suggest larger vectors use the quicksort, unless you want to wait a few days. I find the code fairly concise it makes random numbers depending on the amount you specify for sorting and then outputs the time in seconds to sort the number vector.

It uses an option menu and makes use of
-Bubble Sort
-Selection Sort
-Insertion Sort
-Shell Sort
-Quick Sort

```
#include "iostream.h"
#include "stdlib.h"
#include "time.h"
#include "conio.h"
#include "vector.h"
using namespace std;
// VIEW RESULTS
void view_sort(vector  arr, long max)
{
for(long x=0;x bubble(vector  arr, long max){
int tmp;
for(long i=0;i arr[x+1])
{
//r.push_back(rnd);
tmp = arr[x];
arr[x] = arr[x+1];
arr[x+1] = tmp;
}
}

}
return  arr;
}
// SELECTION SORT
vector  select(vector  arr, long max){
int tmp;
int min;
for(long i=0;i insert(vector  arr, long max)
{
int i, j, index;
for(i=1; i < max;i++)
{
index  = arr[i];
j = i;
while((j > 0) && (arr[j-1] > index))
{
arr[j] = arr[j-1];
j = j-1;
}
arr[j] = index;
}
return arr;
}
// SHELL SORT
vector  shell(vector  arr, long max){

int index, i, j;
for(i=1; i < max;i++)
{
index  = arr[i];
j = i;
while((j > 0) && (arr[j-1] > index))
{
arr[j] = arr[j-1];
j = j-1;

}
arr[j] = index;
}
return arr;
}
/* ######## QUICK SORT ######### */
void quicksort(vector  & arr, int start, int end){
int pivot, starth, endh; // store pivot # keep start & end in memory for split
starth = start;
endh = end;
pivot = arr[start];

while(start < end)
{
while((arr[end] >= pivot) && (start < end))
end--;
if (start != end)
{
arr[start] = arr[end];
start++;
}
while ((arr[start] <= pivot) && (start < end))
start++;
if (start != end)
{
arr[end] = arr[start];
end--;
}
}
arr[start] = pivot;
pivot = start;
start = starth;
end = endh;
if(start < pivot)
quicksort(arr, start, pivot-1);
if(end > pivot)
quicksort(arr, pivot+1, end);
}

/* BEGIN MAIN */
int main(){
time_t start;
long rnd = rand()%1000+1;
vector  r;
//long r;
long tmp;
long maxnum; // if you overload this variable, beware!
int option;
bool stop = false;
bool view = false;
while(!stop){
cout<<"\t\t\tAlgorithms For Sorting Numbers\n"<>option;

// ARRANGE ARRAY
cout<<"Length (<=5000000 )\n";
cin>>maxnum;

if(maxnum == 1)
maxnum = 1000000;

for(long x=0;x>v;
if(v == 1)
{
view = true;
view_sort(r,maxnum);
}
// end program?
cout<>s;
if(s == 0)
stop = true; clrscr();
}
}
``````
Topics:

Opinions expressed by DZone contributors are their own.