An array is a sequential collection of elements of same data type and stores data elements in a continuous memory location. The elements of an array are accessed by using an index. The index of an array of size N can range from  to . For example, if your array size is , then your index will range from 0 to 4 (5-1). Each element of an array can be accessed by using .
Consider following array. The size of this array is . If you want to access , then you can access it by using arr[ 1 ] i.e. .

Array declaration
Declaring an array is language-specific.
For example, in C/C++, to declare an array, you must specify, the following:
- Size of the array: This defines the number of elements that can be stored in the array.
 - Type of array: This defines the type of each element i.e. number, character, or any other data type.
 
A C example would be:
int arr[5];
SORTING
Arranging  data in ascending or descending order is sorting.
Sorting algorithms can be used for collections of numbers, strings, characters, or a structure of any of these types.
Bubble sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.
Assume that  is an unsorted array of  elements. This array needs to be sorted in ascending order. The pseudo code is as follows:
void bubble_sort( int A[ ], int n ) {
    int temp;
    for(int k = 0; k< n-1; k++) {
        // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations
        for(int i = 0; i < n-k-1; i++) {
            if(A[ i ] > A[ i+1] ) {
                // here swapping of positions is being done.
                temp = A[ i ];
                A[ i ] = A[ i+1 ];
                A[ i + 1] = temp;
            }
        }
    }
}
Lets try to understand the pseudo code with an example: 
A [ ] = { 7, 4, 5, 2}
In step 1,  is compared with . Since ,  is moved ahead of . Since all the other elements are of a lesser value than ,  is moved to the end of the array.
Now the array is .
In step 2,  is compared with . Since  and both  and  are in ascending order, these elements are not swapped. However, when  is compared with ,  and these elements are in descending order. Therefore,  and  are swapped.
Now the array is .
In step 3, the element  is compared with . Since  and the elements are in descending order,  and  are swapped.
The sorted array is .
Complexity:
The complexity of bubble sort is in both worst and average cases, because the entire array needs to be iterated for every element.
The complexity of bubble sort is in both worst and average cases, because the entire array needs to be iterated for every element.
No comments:
Post a Comment