Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Sorting

Sorting is the process of arranging g a list of elements in a particular order (Ascending or Descending).
In place sorting vs out place sorting
An in-place sorting algorithm sorts the elements in place: that is, it needs only O(1) extra space. An out-
of-place sorting algorithm needs extra space to put the elements in as it's sorting them. Usually this
means O(n) extra space.
Stable sorting vs unstable sorting
Stable sorting algorithms preserve the relative order of equal elements, while unstable
sorting algorithms don't. ... Stable sorting maintains the order of the two equal balls numbered 8,
whereas unstable sorting may invert the relative order of the two 8s.

Internal vs External Sorting


Internal sorting: If the input data is such that it can be adjusted in the main memory at once, it is called internal
sorting. External sorting: If the input data is such that it cannot be adjusted in the memory entirely at once, it needs
to be stored in a hard disk, floppy disk, or any other storage device
Bubble Sort
Bubble sort algorithm starts by comparing the first two elements of an array and swapping if necessary, i.e., if you
want to sort the elements of array in ascending order and if the first element is greater than second then, you need to
swap the elements but, if the first element is smaller than second, you mustn't swap the element. Then, again second
and third elements are compared and swapped if it is necessary and this process go on until last and second last
element is compared and swapped. This completes the first step of bubble sort.
If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get required
result. But, for better performance, in second step, last and second last elements are not compared becuase, the
proper element is automatically placed at last after first step. Similarly, in third step, last and second last and second
last and third last elements are not compared and so on.
A figure is worth a thousand words so acknowledge this figure for better understanding of bubble sort.

Bubble Sort Logic in C++


int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

Optimized Bubble Sort


int i, j, temp, flag=0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
// introducing a flag to monitor swapping
if( arr[j] > arr[j+1])
{
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
// if swapping happens update flag to 1
flag = 1;
}
}
// if value of flag is zero after all the iterations of inner loop
// then break out
if(flag==0)
{
break;
}
}

You might also like