Make Bubble Sorting more Efficient - java

I have the code for bubble sorting down below. I was wondering how I would be able to run more efficient and loop less amount of times
package bubbleSort;
public class BubbleSort {
public static void main(String[] args) {
// initialize array to sort
int size = 10;
int[] numbers = new int[size];
// fill array with random numbers
randomArray(numbers);
// output original array
System.out.println("The unsorted array: ");
printArray(numbers);
// call the bubble sort method
bubbleSort(numbers);
// output sorted array
System.out.println("The sorted array: ");
printArray(numbers);
}
public static void bubbleSort(int tempArray[]) {
//bubble sort code goes here (you code it)
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++) {
System.out.println(pass);
// loop to control number of comparisions for length of array - 1
for (int element = 0; element < tempArray.length - 1; element++) {
// compare side-by-side elements and swap tehm if
// first element is greater than second elemetn swap them
if (tempArray [element] > tempArray [element + 1]) {
swap (tempArray, element, element + 1);
}
}
}
}
public static void swap(int[] tempArray2,int first, int second) {
//swap code goes here (you code it)
int hold; // temporary holding area for swap
hold = tempArray2 [first];
tempArray2 [first] = tempArray2 [second];
tempArray2 [second] = hold;
}
public static void randomArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
tempArray[i] = (int) (Math.random() * 100) + 1;
}
}
public static void printArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
System.out.print(tempArray[i] + " ");
}
System.out.println("");
}
}
Any help would be greatly appreciated. I am new to coding and have been very stumped on how to improve efficiency and have it loop less times.

Bubble sort is an inefficiency sorting algorithm and there are much better sorting algorithm.
You can make a bubble sort more efficient, its called Optimized Bubble Sort (It is still quite inefficient)
Optimized bubble sort in short is, - you pass n times , but on the every iteration you 'bubble' the biggest (or smallest) element to the end of the array. Now that last item is sorted, so you don't have to compare it again.
I wrote this code last year, not to sure if it still works:
public static void bubbleSort_withFlag(Integer[] intArr) {
int lastComparison = intArr.length - 1;
for (int i = 1; i < intArr.length; i++) {
boolean isSorted = true;
int currentSwap = -1;
for (int j = 0; j < lastComparison; j++) {
if (intArr[j] < intArr[j + 1]) {
int tmp = intArr[j];
intArr[j] = intArr[j + 1];
intArr[j + 1] = tmp;
isSorted = false;
currentSwap = j;
}
}
if (isSorted) return;
lastComparison = currentSwap;
}
}
Here you can read on optimized bubble sort
Here you can find a list of different sorting algorithms that could be more efficient depending on your scenario.

Related

How to show each Iteration Completed in Selection Sort?

I created a program that does a Selection Sort function of array using the elements our input that is given by the user. I am struggling in creating a loop or method to call or show each iteration that is completed to reach the final output of the sorting. I am all open for suggestions. Thanks!
Here's the code :
private static String arrayToString(int[] a)
{
String str="[";
if(a.length>0)
{
str+=a[0];
for(int i=1; i<a.length; i++)
str+="|"+a[i];
}
return str+"]";
}
public static void sort(int[] a)
// Sort the contents of array a in ascending numerical order
{
for(int i=0; i<a.length-1; i++)
{
int pos = smallestPosFrom(i,a);
swap(a,i,pos);
}
}
private static int smallestPosFrom(int from,int[] a)
// Return the index of the smallest element in the section of
// array 'a' from that indexed 'from' to the end of the array
{
int pos=from;
for(int i=from+1; i<a.length; i++)
if(a[i]<a[pos])
pos=i;
return pos;
}
private static void swap(int[] a,int pos1, int pos2)
// Swap the elements indexed pos1 and pos2 within array a
{
int temp;
temp = a[pos1];
a[pos1] = a[pos2];
a[pos2] = temp;
}
And this is how I call them in my main :
System.out.println("The array you entered is:");
System.out.println(arrayToString(Array));
sort(Array);
System.out.println("After sorting, the array is:");
System.out.println(arrayToString(Array));
break;
I'm not sure that I understood you well, but if you would like to see how an array was changed after each iteration of sorting you can just add some print to System.out in 'sort' method:
public static void sort(int[] a)
// Sort the contents of array a in ascending numerical order
{
String arrayAfterIteration;
for (int i = 0; i < a.length - 1; i++)
{
int pos = smallestPosFrom(i, a);
swap(a, i, pos);
arrayAfterIteration = arrayToString(a);
System.out.println("The array after step N" + i + " is:" + arrayAfterIteration);
}
}

Sort an Array - recursive call

I am writing code to sort an array in order. I checked some algorithm for sort and merge, however I found that if I just go through the array and compare every 2 elements and swap them and repeat that until the array is sorted.
So if array[I] > array[i++], swap, repeat.
It is not working so far. I also need a break point to avoid stack overflow: I need some help please
Array:
int[] newArray = new int[] {3,9,5,7,4,6,1};
SortArray s = new SortArray();
s.sortThisArray(newArray, 0, 0);
Recursive function:
public String sortThisArray(int[] array, double counter, double a)
{
int swap0 = 0;
int swap1 = 0;
if (a > 1000)
{
return "reached the end" ;
}
for (int i =0; i<array.length; i++)
{
if (array[i] > array[i++])
{
swap0 = array[i];
swap1 = array[i++];
array[i++] = swap0;
array[i] = swap1;
counter = counter++;
a = array.length * counter;
sortThisArray (array, counter, a);
}
}
for (int j = 0; j<array.length ; j++)
{
System.out.println(array[j]);
}
return "completed";
}
}
What you are searching for is recursive bubble sort algorithm.
The main error is confusing i++ (which increments i every time) with i+1, that is only the position in the array after i, without incrementing. Then, there is no need to use double for counter, and also the a variable is not needed. You need only the length of the current segment, this way:
import java.util.*;
public class RecursiveBubbleSort {
public static void main(String[] args) throws Exception {
int[] newArray = new int[] {3,9,5,7,4,6,1};
sortThisArray(newArray, newArray.length);
System.out.println("Sorted array : ");
System.out.println(Arrays.toString(newArray));
}
public static int[] sortThisArray(int[] array, int n) {
if (n == 1) {
return array; //finished sorting
}
int temp;
for (int i = 0; i < n-1; i++) {
if (array[i+1] < array[i]) {
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
return sortThisArray(array, n-1);
}
}
The ++ operator evalutes separately. So in the case i++, we will read i and then increment it by 1. And the other way around, ++i, would first apply the increment to i, and then read i. So when you want to check for the next element in the array, [i+1] is what you are looking for. With the same reasoning, can you figure out whats wrong with this line?
counter = counter++;
And do we even need it?

Sort Array in Descending order in Java [duplicate]

This question already has answers here:
Java Array Sort descending?
(27 answers)
Closed 5 years ago.
This array Sorts the number in Ascending and prints the output. I wanna change it to descending, but i can't figure it out.. i tried changing the + to - but it didn't seem to work.. Can someone tip me on how to do it?
public class ArraysSorting {
public static void main(String[] args) {
int [] scores = { 5,8,2,9,3};
sortArrayDesc (scores, scores.length);
}
public static void sortArrayDesc( int [] list, int listLength) {
int index;
int smallestIndex;
int minIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
smallestIndex = index;
for (minIndex = index + 1;
minIndex < listLength; minIndex++)
if (list[minIndex] < list[smallestIndex])
smallestIndex = minIndex;
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
//display data after sorting
System.out.print("sorted array");
for (index=0; index<listLength; index++) {
System.out.print(list[index] + ",");
}
}
}
I suggest you look up articles on "bubble sort", which is fairly close to what you are doing here. Then, follow up with learning how other sort algorithms work. You generally do not want to use an n-squared sort algorithm.
To do the sort in the reverse order, you would want to use the smallestIndex variable to store the largest index instead. Change the name there, and use the > operator on the line if (list[minIndex] < list[smallestIndex]) to find the biggest number. You will then be storing the largest number in the first list position and the smallest in the last list position.
The updated loops would look like:
for (index = 0; index < listLength - 1; index++)
{
biggestIndex = index;
for (minIndex = index + 1; minIndex < listLength; minIndex++)
if (list[minIndex] > list[biggestIndex])
biggestIndex = minIndex;
temp = list[biggestIndex];
list[biggestIndex] = list[index];
list[index] = temp;
}
A simple way to modify this code to sort array in descending order is to change the comparison operator from smaller than (<) to larger than (>).
Your code:
if (list[minIndex] < list[smallestIndex])
Change to:
if (list[minIndex] > list[smallestIndex])
You should also change the variable naming otherwise it does not make sense.
It sounds like you want a "for loop" to run in reverse:
for (i = listLength; i>0; i--) {
System.out.print(list[i] + ",");
}
You need to start with
list[listLength]
and increment down until you get to the beginning of the list/array which is
list[0].
I just made a few modifications. Changed the variable name and the important part
if (list[maxIndex] > list[largestIndex]) // changed less than sign to greater than
public class ArraysSorting {
public static void main(String[] args) {
int [] scores = { 5,8,2,9,3};
sortArrayDesc (scores, scores.length);
}
public static void sortArrayDesc( int [] list, int listLength) {
int index;
int largestIndex;
int maxIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
largestIndex = index;
for (maxIndex = index + 1;
maxIndex < listLength; maxIndex++)
if (list[maxIndex] > list[largestIndex])
largestIndex = maxIndex;
temp = list[largestIndex];
list[largestIndex] = list[index];
list[index] = temp;
}
//display data after sorting
System.out.print("sorted array");
for (index=0; index<listLength; index++) {
System.out.print(list[index] + ",");
}
}
}

Why is my selection sort algorithm not working?

I'm trying to make a selection sort algorithm in java that finds the smallest element of an unsorted array and puts it on the end of a new array. But my program only copies the first element twice, gets the next one, and then the rest is all zeroes:
public static int find_min(int[] a){
int m = a[0];
for (int i = 0; i < a.length; i++){
if (m > a[i])
m = a[i];
}
return m;
}
public static int[] selectionSort(int[] unsorted){
int[] c = new int[unsorted.length];
for(int i = 0; i < unsorted.length; i++){
int smallest = find_min(unsorted);
c[i] = smallest;
unsorted = Arrays.copyOfRange(unsorted, i+1, unsorted.length );
}
return c;
}
When I put in something like:
public static void main(String[] args){
int a[] = {1,-24,4,-4,6,3};
System.out.println(Arrays.toString(selectionSort(a)));
}
I get:
[-24, -24, -4, 0, 0, 0]
where is this going wrong? Is this a bad algorithm?
Ok, let's revisit the selection sort algorithm.
public static void selectionSort(int[] a) {
final int n = a.length; // to save some typing.
for (int i = 0; i < n - 1; i++) {
// i is the position where the next smallest element should go.
// Everything before i is sorted, and smaller than any element in a[i:n).
// Now you find the smallest element in subarray a[i:n).
// Actually, you need the index
// of that element, because you will swap it with a[i] later.
// Otherwise we lose a[i], which is bad.
int m = i;
for (int j = m + 1; j < n; j++) {
if (a[j] < a[m]) m = j;
}
if (m != i) {
// Only swap if a[i] is not already the smallest.
int t = a[i];
a[i] = a[m];
a[m] = t;
}
}
}
In conclusion
You don't need extra space to do selection sort
Swap elements, otherwise you lose them
Remembering the loop invariant is helpful

Error with Selectionsort

I've tried many different variations, and I keep getting the same problem. After selectio nsort runs, the number of items outputted, does not match the size of my array. I've been running through with any array of size 10, yet the output does not contain 10 numbers. However, the output of selection sort is sorted.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Sorts {
public static Integer[] createArray(int size) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < size; i++)
list.add(i);
Collections.shuffle(list);
Integer[] array = list.toArray(new Integer[list.size()]);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
return array;
}
public static void selectionSort(Integer[] array) {
Integer min;
for (Integer i = 0; i < array.length - 1; i++) {
min = i;
for (Integer j = i + 1; j < array.length; j++) {
if (array[j].compareTo(array[min]) > 0) {
min = j;
}
}
if (min != i) {
Integer temp = array[i];
array[i] = array[min];
array[min] = temp;
System.out.print(array[i]);
}
}
}
public static void main(String args[]) {
int number = 10;
Integer[] list = createArray(number);
System.out.println("");
selectionSort(list);
}
}
Whenever you make a swap, you print out a number. But in an array of 10 elements, you'll only make 9 swaps -- the final element will already be in its correct place! To fix this, add System.out.print(array[array.length - 1]); to the end of your function.
Also, if the minimum element happens to be i, then no swap will be performed and no element printed. This still sorts the array, but if you want it to be printed out, you could remove the if (min != i) statement and simply do a swap on every pass through the list.
You should also take a look at using ints rather than Integers. An Integer is generally slower than an int and you usually only use them when Java wants an object.

Categories