enh(Java): more optimized way of bubble-sort (#321)
parent
18c60bf2d5
commit
12138da6cb
|
@ -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+" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue