Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add descending order for bubblesort in java #180

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 63 additions & 34 deletions Java/BubbleSort.java
Original file line number Diff line number Diff line change
@@ -1,39 +1,68 @@
import java.util.Scanner;

public class BubbleSort {
public class BubbleSort {

static void bubbleSortAsc(int arr[], int n) {
int tmp;
boolean flag;

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter " + n + " elements :");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
for (int i = 0; i < n - 1; i++) {
flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = true;
}
}
if (!flag)
break;
}
}

static void bubbleSortDesc(int arr[], int n) {
int tmp;
boolean flag;

bubbleSort(arr);

System.out.println("\nThe sorted array : ;");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}

static void bubbleSort(int arr[]) {
int len = arr.length, tmp;
boolean flag;
for (int i = 0; i < len; i++) {
flag = false;
for (int j = 0; j < len - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = true;
}
}
if (!flag)
break;
}
}
for (int i = 0; i < n - 1; i++) {
flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = true;
}
}
if (!flag)
break;
}
}

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Indicate the number of elements: ");
int order;
boolean asc;
int n = sc.nextInt();
int arr[] = new int[n];

System.out.println("Type " + n + " numbers: ");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();

System.out.println("Indicate desired order (0 for Ascending, 1 for Descending):");
order = sc.nextInt();
asc = order == 0 ? true : false;
if (asc)
bubbleSortAsc(arr, arr.length);
else
bubbleSortDesc(arr, arr.length);
System.out.println("The sorted array : ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
sc.close();
}
}