Topic: Sorting
Questions Successfully Completed: 2
1) Bubble Sort | Easy |
2) Binary Array Sorting | Easy |
Bubble Sort
Time Complexity : O(n2)
Space Complexity : O(1)
Question
Input: N = 5 arr[] = {4, 1, 3, 9, 7} Output: 1 3 4 7 9
private static int[] bubble(int[] arr,int n){
boolean swapped = false;
for(int i=0;i<n-1;i++){
swapped = false;
for(int j=0;j<n-1-i;j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1]= temp;
swapped = true;
}
}
if(swapped == false){break;} // rest of the list is already sorted at this point, in case of sorted list
}
return arr;
}
Binary Array Sorting
Time Complexity : O(n)
Space Complexity : O(1)
Question
Input: 5 1 0 1 1 0 Output: 0 0 1 1 1 Explanation: After arranging the elements in increasing order, elements will be as 0 0 1 1 1.
static void binSort(int arr[], int n)
{
int countzero=0;
int countone=0;
for(int i=0;i<n;i++){
if(arr[i]==0){
countzero++;
}
else{countone++;}
}
int j=0;
for(j=0;j<countzero;j++){
arr[j]=0;
}
for(int k=j;k<n;k++){
arr[k]=1;
}
}
Thank you for Reading! :)