Switch Bubble Sort from Increasing to decreasing - java

I need to switch from increasing to decreasing. Here is what I have:
public static void bubbleSort(double[] array) {
boolean swapping = true;
for (int i = 1; i < array.length && swapping; i++) {
// array is already sorted if no swapping happened in the previous inner loop
swapping = false; // assume no swapping, before entering the inner loop
for (int j = 0; j < array.length - i; j++) {
if (array[j] > array[j + 1]) {
double temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapping = true;
}
}
}
printArray(array);
}

Related

Selection sort in descending order - JAVA

I have a selection sort implemented to sort an array of random integers. I would like the user to choose between ascending or descending order. The ascending sort works flawlessly, although descending does not. Here is what my selection sort looks like:
public String selection(int[] array,int num,String order) {
String output = "";
int min;
// This is the descending selection sort
if (order == "desc") {
for (int i = num - 1; i >= 0; i--) {
// Assume first element is min
min = i;
for (int j = i + 1; j < num; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) {
final int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
output = output + Integer.toString(array[i]) + "\n";
}
} // This is the ascending selection sort
else {
for (int i = 0; i < num; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < num; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) {
final int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
output = output + Integer.toString(array[i]) + "\n";
}
}
return(output.trim());
}
I've seen a few questions similar to mine, although none of the questions I saw had their selection sort set up like this so I was unable to implement their solutions.
Firstly, the if blocks should compare to minPosition and maxPosition, not i. Secondly, if you are selecting both minimum and maximum, then your inner for loop should stop at a.length - i, not a.length (since the top i elements are also sorted). Doing both gives you this as the ascending order algorithm.
public static void SortAscending(int[] a){
for(int i = 0; i < a.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length - i; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
/*
if(i < a.length/2-1)
*/
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
}
To switch to descending order, simply add one line.
public static void SortDescending(int[] a){
for(int i = 0; i < a.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length - i; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
/*
if(i < a.length/2-1)
*/
swap(a,minPosition,maxPosition); // <-- this line
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
}
Use swap function https://www.geeksforgeeks.org/collections-swap-method-in-java-with-examples/

Number of Comparisons in Bubble Sort

I am trying to make a method for comparisons in my bubble sort class. However, I keep getting the same value. Is there any way to fix this? Thanks.
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - i - 1; j++)
{
count++;
if ((array[i] > array[i + 1])) //Swaps the elements
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
The inner loop index j is not used, and it has incorrect bounds.
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = i; j < array.length - 1; j++)
{
count++;
if ((array[j] > array[j + 1])) //Swaps the elements
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
The outer loop index i is the same value for all the values of j in the inner loop. Looks like the compare logic should be using the inner loop index j.
If count is supposed to record the number of swaps done during the sort, perhaps it needs to be in the block of code performing the swap. At the moment, count++ will always execute the same number of times.
Try this:
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - i - 1; j++)
{
if ((array[i] > array[i + 1])) //Swaps the elements
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
count++;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
You better try to increment value of count inside the if-condition. You can place count++ anywhere inside if-condition, based upon requirements.

How to print steps when sorting in Java?

I have one problem. I need to print time and steps of sorting. I did time but I do not how to print steps.
class BubbleSort {
public static void main(String[] args) {
int[] randomNums = new int[20];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (100 * Math.random());
}
System.out.println("Numbers before sorting: ");
for (int i = 0; i < randomNums.length; i++) {
System.out.print(randomNums[i]+" " );
}
System.out.println();
long time = System.nanoTime();
bubbleSort(randomNums);
long elapsed = System.nanoTime() - time;
System.out.println("\nBubble sort time is " + elapsed + " nanoseconds passed, " + elapsed / 1000000000 + " seconds passed");
}
static void bubbleSort(int[] arr) {
int numbers = arr.length;
int temp = 0;
for (int i = 0; i < numbers; i++) {
for (int j = 1; j < (numbers - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
}
For listing down steps we can simply use a sysout to do the thing. The crux here is to know how this sorting algo is actually doing the sorting part. The swapping part is the actual sort code.
int step = 0;
for (int i = 0; i < numbers; i++) {
for (int j = 1; j < (numbers - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
System.out.println("step #" + step + ". swapping " + arr[j - 1] + " and " + arr[j])
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
step++;
}
}
}

Why can't we change the order of statements in insertion sort's while loop?

As shown below is the basic insertion sort algorithm taught at school. if you change the order of while loop parameters, it doesn't work.
public static int[] insertionSort(int[] A){
for(int i =1; i<A.length;i++){
int key = A[i];
int j = i;
while(j>0&&A[j-1]>key){
A[j]=A[j-1];
j--;
}
A[j]=key;
}
return A;
}
After the change (Now the code wont work and it will give java.lang.ArrayIndexOutOfBoundsException: -1 expection):
public static int[] insertionSort(int[] A){
for(int i =1; i<A.length;i++){
int key = A[i];
int j = i;
while(A[j-1]>key&&j>0){
A[j]=A[j-1];
j--;
}
A[j]=key;
}
return A;
}
If there any other way to implement the same algorithm so that the order of the conditional loop statements doesn't matter?
Because of short-circuit evaluation.
If the first half of an && is false, the second half will not be evaluated at all (since the result cannot possibly be true).
Therefore, you can write j > 0 && A[j - 1]..., and A[j - 1] will only be evaluated if j > 0.
You can improve the above code as follow. Now the while loop will never fail for arr[-1] condition as every time j==-1 the loop will break out.
public static void InsertionSort()
int j, temp;
Scanner sc = new Scanner(System.in);
System.out.println("enter the size");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("enter the elements");
for (int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
for (int i = 1; i < n; i++)
{
temp = arr[i];
j = i - 1;
while (arr[j] > temp && j >= 0)
{
arr[j + 1] = arr[j];
j = j - 1;
if (j == -1)
break;
}
arr[j + 1] = temp;
}
System.out.println("Array Sorted through Insertion Sort");
for (int i = 0; i < n; i++)
{
System.out.println(arr[i]);
}
}

How to find correct position to insert an element in a sorted array?

I have to make a program in Java to create a sorted array in descending order. When i try to insert 10, 3 it is ok, but when i insert 10, 3, 8 the result is 10, 8, 0. For some reason the 0 appears on the end. Also when i try to imput negative numbers like -2 the result becomes -2, 8, 0. Can someone help? Also, is bubble sort the correct method for this kind of insertion? (Sorry for my english it is my first time here). Thank you for your time.
private int searchPosition(int a)
{
int position = 0;
for (int i = 0; i < array.length(); i++)
{
if(array[i] != a)
{
if((array[i] > a) && (array[i + 1] < a))
{
position = i + 1;
}
}
else
{
position = i;
}
}
return position;
}
public boolean insert(int a)
{
int position;
boolean exists;
int temp;
if (size == capacity)
{
System.out.println("The array is full.");
return false;
}
else
{
exists = //here i call a method to make sure the element to insert doesn't exist in the array
if (exists == false)
{
//Bubble Sort in desceding order
for (int i = 0; i < array.length(); i++)
{
for (int j=0; j < array.length() - i; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
position = searchPosition(a);
//move elements one position to the right
for (int i = array.length(); i < position; i--)
{
array[i] = array[i - 1];
}
array[position] = a;
//place a in the free position
size++;
return true;
}
else
{
System.out.println("The element" + a + " already exists in the array.");
return false;
}
}
}
You can do this with a break statement, where you exit the loop when a value is smaller then a value in the array and use this index.
int value = 8;
for(int i = 0; i < array.length; i++) {
if(array[i] < value) {
break;
}
}
for(int j = array.length; j > i; j--) {
a[j] = a[j -1];
}
a[j] = value;
size++;

Categories

Resources