Write a program to sort an array. Use of bubble sort.
Example 1:
Input: arr[]= {3,2,5,4,1}
Output: 1 2 3 4 5
Approach:
Java
import java.util.Arrays;public class BubbleSort {public static void main(String args[]) throws Exception {int arr[] = { 3, 2, 5, 4, 1 };bubbleSorting(arr, arr.length);}static void bubbleSorting(int[] arr, int N) {for (int i = 0; i < N; i++) {for (int j = 0; j < N - i - 1; j++) {if (arr[j] > arr[j + 1]) {// Swapping elementint tmp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = tmp;}}}// Sorting array printingArrays.stream(arr).forEach(e -> System.out.print(e + " "));}}//Time Complexity: O(n^2)//Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//Function to sort the given//arrayvoid bubbleSort(int arr[],int n){for(int i=0;i<n-1;i++){for(int j=0;j<n-i-1;j++){if(arr[j]>arr[j+1]){int temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}}int main(){int arr[]={3,2,5,4,1};int n=sizeof(arr)/sizeof(arr[0]);bubbleSort(arr,n);cout<<"Sorted Array is ";for(int i=0;i<n;i++)cout<<arr[i]<<" ";return 0;}//Time Complexity: O(n^2)//Space Complexity:O(1)
No comments:
Post a Comment