enh(Java): more optimized way of bubble-sort (#321)

pull/322/head
Shivam Gupta 2021-05-24 17:54:21 +05:30 committed by GitHub
parent 18c60bf2d5
commit 12138da6cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 35 additions and 22 deletions

View File

@ -1,27 +1,40 @@
import java.util.Scanner;
import java.util.Arrays; public class sorting {
public class BubbleSort {
static int temp = 0;
static int[] nums = { 13, 34, 12, 45, 56, 32, 20 };
public static void main(String[] args) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Before Sorting : "+Arrays.toString(nums)); boolean sorted = true;
sort();
System.out.println("Enter the size of array: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the elements of array : ");
for (int i=0;i<n;i++)
{
a[i]=sc.nextInt();
} }
//create method sorting array
public static void sort() { for (int i=0;i<n-1;i++)
for (int i = 1; i < nums.length; i++) { {
for (int j = 0; j < i; j++) { for(int j = 0; j < n - 1 - i; j++)
if (nums[j] > nums[i]) { {
temp = nums[j]; if(a[j+1]<a[j])
nums[j] = nums[i]; {
nums[i] = temp; int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
sorted =false;
}
}
if(sorted)break;
}
System.out.println("Array after sorting :");
for (int item:a)
{
System.out.print(item+" ");
} }
} }
} }
System.out.println(Arrays.toString(nums));
}
}