[IN C WITH COMMENTS]The bubble sort is another technique for sorting an array. A
ID: 3814157 • Letter: #
Question
[IN C WITH COMMENTS]The bubble sort is another technique for sorting an array. A bubble sort compares adjacent array elements and exchanges their values if they are out of order. In this way, the smaller values bubble to the top of the array (toward element 0), while the larger values sink to the bottom of the array. After the first pass of a bubble sort, the last array element is in the correct position; after the second pass the last two elements are correct, and so on. Thus, after each pass, the unsorted portion of the array contains one less element. Write and test a function that implements this sorting method.
Explanation / Answer
// Implementation of Bubble sort in C
// Function To Swap the element
void Element_Swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
// Reference of each element is pass to Swap an element
Element_Swap(&arr[j], &arr[j+1]);
}
---------------------------------------------------------------------------------------------------------------------------------------------------------
Test of Above Function-----------------------------
Enter array elements :10 4 55 21 6
Unsorted Data: 10 4 55 21 6
After pass 1 : 4 10 21 6 55
After pass 2 : 4 10 6 21 55
After pass 3 : 4 6 10 21 55
After pass 4 : 4 6 10 21 55
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.