Computer Programming web Web programming Tips



The two directions bubble sort algorithm - C++ source code

By Sergey Skudaev

Happy Amazon Prime Day July 12 - Exclusive Deals for Prime Members - Start Free 30-Day Trial


Precondition:  The function accepts an unsorted array  []  and integer size that is the size of the array.

Post condition:  Sorted array

The function performs the two direction bubble sort. It starts from the head and from the tail of the array and compares two adjusted cells. If the numbers are not in order, they are exchanged.

After each pass, the array becomes shorter by one cell from the head and by one cell from the tail.  

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

int*  TwoBubbleSort ( 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=TwoBubbleSort (i,array);

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


int* TwoBubbleSort ( int size, int array [] ) { int current = 0; int* pointer; bool sorted = false; pointer=array; while (( current < size )&&( sorted == false )) { int walker1 = size -1; // walks from the tail to the head int walker2 = current; // walks from the head to the tail sorted = true; while ( walker1 > current ) { if ( array [walker1] < array [walker1-1] ) { sorted = false; exchange ( array, walker1, walker1-1 ); } walker1 = walker1 - 1; if ( array [walker2] > array [walker2 + 1] ) { sorted = false; exchange ( array, walker2, walker2 + 1 ); } walker2 = walker2 + 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; }

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
What is the opposite word of small?
 
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

My eBooks on Amazon.com

Learn C++ Programming By Examples

Learn SQL Programming By Examples

Learn PHP Programming by Examples

Visual Basic Programming By Examples

How to Build Your Own Web Site from Scratch