Problem Statement: Given an Array, print the number of rounds
needed in bubble sort
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } bool isSorted(int arr[], int n) { for (int i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { return false; } } return true; } int bubbleSort(int arr[], int n) { int i, j; int flag; int rounds = 0; if (isSorted(arr, n)) { return 0; } else { for (i = 1; i < n; i++) { for (j = 0; j < n - 1; j++) { if (arr[j] > arr[j + 1]) { swap(&arr[j], &arr[j + 1]); } } rounds = i; if (isSorted(arr, n)) { return i; } } } return rounds; } int main() { int i, n; printf("\nEnter number of elements:"); scanf("%d", &n); int arr[n]; printf("\nEnter elements:"); for (i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("\nBubble sort rounds:\t%d", bubbleSort(arr, n)); //printArray(arr,n); return 0; }
$bubbleSortR.c $ ./a.out Enter number of elements:3 Enter elements: 3 2 1 Bubble sort rounds: 2 $ ./a.out Enter number of elements:3 Enter elements: 1 3 2 Bubble sort rounds: 1 $ ./a.out Enter number of elements:3 Enter elements: 1 2 3 Bubble sort rounds: 0 $ |
Time complexity:O(n2)
also see
C Programming language |
Go Programming language |
Linked List | Array |
Stack | Queue |
Puzzle | Reasoning |
Aptitude | HTML |