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