Topic :Some Useful example of Arrays: Bubble Sort. Quicksort.



Sorting An Array:

Sorting is the Process to Arrange the Elements within a Sequence into a particular Order. For Example, a Sequence of integers may be Arranged in Ascending order (that is, from smallest to Largest). A Sequence of words (strings) may be arranged in Lexicographical (commonly called alphabetic) Order.

There are several different ways to sort Arrays. Some perform much better than others. in this tutorial we will discuss about-



The basic goal of each method is to compare each array element to another array element and swap them if the higher value is less than the other.



Bubble Sort:

The Bubble sort is one of the easiest sorting way to understand. In Bubble sort the values in the Array are compared to each other, a pair at a time, and swapped if they are not in back-to-back order. the lowest value eventually floats to the top of the Array, like a bubble in a glass of soda. The Bubble sort steps through the Array and compares pairs of numbers to determine whether they have to be swapped. Several Passes might have to made through the Array before it is finally sorted (No more passes are Needed).

Let's Create an Program which can sort our Number. in this Program we will Enter some Numbers in Program and our Program will return us the sorted Numbers (Ascending Order). We will create an sort() function, this function will sort our data.



/*Bubble Sort function - InfoBrother*/
 
void sort(int *A,int n) //1st arguments for array and 2nd for total number
{
    int temp; //temporarily Variable:
    for(int i=0;i<=n;i++) //loop for sorting
    {
        for(int j=0;j<n-1;j++) //2nd loop for sorting
        {
            if(A[j]>A[j+1]) //if n is greater then N+1; then do swapping
            {
                temp=A[j];
                A[j]=A[j+1];
                A[j+1]=temp;
            }
        }
    }
}

Above, there is an Sorting Function. this function will Get two Arguments, first will be Array, and second will total Number of Item.

»
In The Function there are two Loops. the Inner Loop checks adjacent elements in the Array, looking for out-of-order elements. When an out-of-order element pair is found, the two elements are exchanged. With pass, the smallest element of those remaining moves into its proper location. The outer loop causes this process to repeat until the entire array has been sorted.

»
There is an if-statement, which will check the order of number, if there is any number out of order, it will swap the Numbers. Let's try to Understand, how it will swap numbers in Arrays:


if (A[j] > A[j+1])

As the array store data in Sequence, start from 0 to so on. here the starting address of Array is A[ j ] , Next will be A[ j+1 ] , and Next, A[ j+2 ] and so on. as shown in the given table.



A[ j ]A[ j+1 ]A[ j+ 2]A[ j+3 ]A[ j+4 ]......A[ j+n ]


So in this Program our if-statement will check Whether the first Number A[ j ] is greater than second Number A[ j+1 ] . If first Number will greater than second Number. Then If-statement will Perform following task.


  • 1 » temp is an Temporally Variable. Assignment Operator ( = ) will assign the value store in A[ j ] to temp variable.


    temp = A[ j ];


    2 » Then the Value stored in A[ j ] will replace by the value of A[ j+1 ]


    A[ j ] = A[ j+1 ];


    3 » At the end, the Value stored in A[ j+1 ] will replace by the value of temp.


    A[ j+1 ] = temp;


In Simple - Let's suppose we have three Rooms Room1, Room2 and Room3. and we want to shift Furniture from room1 to room2, and from room2 to room1 (Interchanging). In this case, first of all we Need to Remove all furniture from Room2, so we will take an empty room that is room3, and shift all furniture from room2 to room3, Now our room2 is empty so we can shift our furniture from room1 to room2, so we did. at the end we will transfer our furniture from room3 to room1. that's all about bubble sort.


Room3   =   Room2;
Room2   =   Room1;
Room1   =   Room3;


Let's have an Complete Bubble sort Example: in this Example User will enter some Numbers, and our program will print these all Number in Ascending Order ( 1,2,3,4,5 to so on) using sorting Function Sort();


/*sorting Arrays: Bubble Sort: InfoBrother*/
 
#include<iostream>
using namespace std;
 
/* This function have two arguments, 1st for Array and 2nd for size for array*/
void sort(int*,int); //Prototype for Sorting Function. 
 
main()
{
    int size=10; //size of Array;
    int *ptr; //ptr is an Pointer to Integer.
    int num[size]; //Array of int.
    ptr = num; //ptr point to starting address of Array. ( num[0] ).
 
    if(ptr!=NULL) //Error chacker, if ptr didn't point to Array.
    {
        cout<<" Enter 10 Digits "<<endl;
        for(int i=0;i<=10;i++) //loop to get all numbers from user
        {
            cin>>ptr[i];
        }
    }
    sort(ptr,size); // sorting function call. 
 
    cout<<" Sorted Data: " ;
    for(int i=0;i<=10;i++) //loop will print all sorted Numbers:
    {
       cout<<ptr[i]<<" | ";
    }
 
	return 0;
}
 
/*Sort Function Defination.*/
void sort(int *A,int n) //1st arguments for array and 2nd for total number
{
    int temp; //temporarily Variable:
    for(int i=0;i<=10;i++) //loop for sorting
    {
        for(int j=0;j<10;j++) //2nd loop for sorting
        {
            if(A[j]>A[j+1]) //if n is greater then N+1; then do swapping
            {
                temp=A[j];
                A[j]=A[j+1];
                A[j+1]=temp;
            }
        }
    }
}


Quicksort:

The Bubble sort is the small and easy way to sort Data, but it is not efficient when used on larger ones. The best General-purpose sorting algorithm is the Quicksort. The Quicksort, however, is difficult to understand for you as a beginner. But still, we are going to discuss Quicksort function here.

The Quicksort, invented and named by C.A.R. Hoare, is the best general-purpose sorting algorithm currently available. the standard library < stdlib.h > contains a Function called Quicksort qsort(). So make sure, to include stdlib in your header of Program.

The Function sorts an Array of "n" elements whose first element is pointed to by Array. The size of each element is specified by size. the comparison function pointed to by compare is used to sort the content of the Array in ascending order. qsort() calls the function with two arguments that point to the element being compared.


int compare(const void* a, const void* b);

This is another function, will call by qsort function to compare two Numbers by using pointer. qsort will call this function, and this function will compare two numbers. and will -

  • » Return Positive ( + ), if ranked is higher. (firstNumber > secondNumber)
    » Return Negative ( - ) if ranked is lower. (firstNumber < secondNumber)
    » Return zero ( 0 ) if ranked is same. (firstNumber == secondNumber)



qsort(ArrayName, Size, dataSize, CompareFunctionCalling);

This is the calling of qsort function in our Program, and the definition of this function is define in stdlib library. The qsort function Need four arguments.


  • Title

    » ArrayName: It's the name for array.
    » Size: Second Argument is the size of Array, ForExample - Array[ 12 ] the Array size is 12.
    » dataSize: Third Argument is the data Size. like size of int, size of char, or anyother data Type. we can use sizeof Operator to know the size of data type.
    » CompareFunctionCalling: Forth Argument is the Compare Function, that we discussed above.



/*sorting function using qsort function- InfoBrother */
 
#include<iostream>
#include<stdlib.h>//sort function is define here.
using namespace std;
 
int compare(const void* a, const void* b)
{
    int  A=*((int*)a); //1st pointer for dereference, and other for cast
    int  B=*((int*)b);
 
    return A-B; //same as, return +, if ranked higher,
     //return - if ranked is lower and 0 if ranked same;
}
 
main()
{
    int A[10]; //size of Array.
    cout<<"Enter 10 digits: "<<endl;
    for(int i=0; i<10; i++) //loop to Get data From user.
    {
        cin>>A[i];
    }
    qsort(A,10,sizeof(int),compare); //qsort function calling to sort array
 
    cout<<"Sorted Data: ";
    for (int i=0;i<10;i++) //loop to display sorted Array.
    {
        cout<<A[i]<<" | ";
    }
 
    return 0;
}





I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement