Computer Programming web Web programming Tips



The Two Directional Selection Sort Algorithm - C++ code

By Sergey Skudaev




Precondition:  The TwoDirectionSelSort accepts two parameters: unsorted array [] and integer size that is the size of the array.  

Post condition: Sorted array.

The function sorts the array in two directions. It checks if the current number is the smallest or the largest one. If it is the smallest, the number is moved to the front of the array.

If it is the largest, the number is moved to the end of the array. After each pass, the array becomes shorted by one number from the front and by one number from the end of the array

#include "stdafx.h"
#include <iostream.h>

int* TwoDirectionSelSort ( int size, int array [] );
void exchange (int array[], int a, int b);


int main(int argc, char* argv[])
{

int array[10];
int i=0;

 while (i < 10)
{

cout<<"Please enter a number."<<endl;
cin>>array[i];
i++;

}
				cout<<"Unsorted array:"<<endl;
				for(int k=0; k<10;k++)
                cout<<array[k];
				cout<<endl;

 //call the sorting function
 int* arr=TwoDirectionSelSort(i,array);

				cout<<"Sorted array:"<<endl;
				for(int n=0; n<10;n++)
                cout<<arr[n];
				cout<<endl;
return 0;
 }



int* TwoDirectionSelSort ( int size, int array [] ) { int current = 0; bool sorted = false; int* pointer; pointer=array; while ((current < size-1) && (sorted == false)) { int smallest = current; // the first element of the array int largest = size - 1; // the last element of the array int walker = current +1; sorted = true; if ( array [smallest] > array [largest] ) { exchange ( array, smallest, largest ); sorted = false; } while( walker < size ) { if ( array [walker] < array [smallest] ) { exchange ( array, walker, smallest ); sorted = false; } if ( array [walker] > array [largest] ) { exchange( array, walker, largest); sorted = false; } walker = walker + 1; } current = current + 1; size = size -1; } return pointer; } void exchange (int array[], int a, int b) { int temp=array[a]; array[a]=array[b]; array[b]=temp; }

Demo Java Applet

My eBooks on Amazon.com



Subscribe to our mail list to receive free code examples.

Comments

No comments yet.

Add Comment

* Required information
(never displayed)
 
Smile Sad Huh Laugh Mad Tongue Crying Grin Wink Scared Cool Sleep Blush Unsure Shocked
 
1000
Enter the word shark backwards.
 
Enter answer:
Captcha
Refresh
 
Enter code:
 
Notify me of new comments via email.
 
Remember my form inputs on this computer.
 
I have read and understand the privacy policy. *
 
I have read and agree to the terms and conditions. *
 
 
Powered by Commentics