Skip to content

Commit e5dd6ef

Browse files
authored
Updated to more efficient version if array size is scaled.
Changed loop from "for" to "do-while". Added decrement at end of do loop to decrease size of array tested after each iteration.
1 parent 1bd077e commit e5dd6ef

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

Sorts/BubbleSort.java

+21-13
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,12 @@ class BubbleSort
1616
*/
1717
public static void main(String[] args)
1818
{
19-
int array[]=new int[6];
19+
int size = 6;
20+
int array[]=new int[size];
21+
boolean swap;
22+
int last = size - 1;
2023
Scanner input=new Scanner(System.in);
24+
2125

2226
//Input
2327
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
@@ -27,18 +31,22 @@ public static void main(String[] args)
2731
}
2832

2933
//Sorting
30-
for(int i=0; i<5; i++)
31-
{
32-
for(int j=i+1; j<6; j++)
33-
{
34-
if(array[j]>array[i])
35-
{
36-
int temp=array[j];
37-
array[j]=array[i];
38-
array[i]=temp;
39-
}
40-
}
41-
}
34+
do
35+
{
36+
swap = false;
37+
for (int count = 0; count < last; count++)
38+
{
39+
if (array[count] > array[count + 1])
40+
{
41+
int temp = array[count];
42+
array[count] = array[count + 1];
43+
array[count + 1] = temp;
44+
swap = true;
45+
}
46+
}
47+
48+
last--;
49+
} while (swap);
4250

4351
//Output
4452
for(int i=0; i<6; i++)

0 commit comments

Comments
 (0)