AllAlgorithms / c

Implementation of All ▲lgorithms in C Programming Language
https://github.com/AllAlgorithms/c
MIT License
1.58k stars 534 forks source link

Bubble Sort #440

Open bca072024 opened 4 months ago

bca072024 commented 4 months ago

Write a c program to sort array using bubble sort

include

include

void main() { int arr[30],i,n; void bubble_sort (int[],int); printf("\nEnter no of elements"); scanf("%d",&n); printf("\nEnter %d value",n); for(i=0;i<n;i++) scanf("%d",&arr[i]); printf("\nBefore sorting elements are"); for(i=0;i<n;i++) printf("%d ",arr[i]); bubble_sort(arr,n); printf("\nAfter sorting elements are"); for(i=0;i<n;i++) printf("%d ",arr[i]); } void bubble_sort (int arr[],int n) { int temp,i,j; for(i=0;i<n;i++) { for(j=0;j<n-1;j++) { if (arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } }

Raja-Muhammad-Bilal-Arshad commented 1 month ago

//Write a c program to sort array using bubble sort:

include

// Function to perform bubble sort void bubbleSort(int arr[], int n) { int i, j, temp; // Loop through each element in the array for (i = 0; i < n - 1; i++) { // Last i elements are already in place for (j = 0; j < n - i - 1; j++) { // Swap if the element found is greater than the next element if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }

// Function to print the array void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); }

// Main function int main() { int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: \n");
printArray(arr, n);

bubbleSort(arr, n);

printf("Sorted array: \n");
printArray(arr, n);

return 0;

}