I am having issues with getting a simple bubble sort of an array to work properly.
It compiles, but I'm getting an out of bounds exception when running the program.
I know what an out of bounds error is but I can't see why it occurred in this case.
Any geniuses there that know how to fix this? Thank you
public class BubbleSort
{
public static void main(String[] args)
{
// create the array that we want to sort with buble sort alogorithm
int intArray[] = new int[]{5, 90, 35, 45, 150, 3};
//print the array before the bubble sort
System.out.println("Array before Bubble Sort");
for (int i = 0; i < intArray.length; i++)
{
System.out.print(intArray[i] + " ");
}
// sort an array using bubble sort algorithm
bubbleSort(intArray);
System.out.println("");
// print array after sorting using bubble sort
System.out.println("Array after Bubble Sort");
for (int i = 0; i < intArray.length; i++)
{
System.out.print(intArray[i] + "");
}
}
private static void bubbleSort(int[] intArray)
{
int n = intArray.length;
int hold = 0;
for (int i = 0; i < n; i++) //allows us to pass or loop around array
{
for (int j = 1; j < (n - i); j++) //allows on pass or comparison
{
if (intArray[j] > intArray[j + 1]) //swap the elements!
{
hold = intArray[j];
intArray[j] = intArray[j + 1];
intArray[j + 1] = hold;
}
}
}
}
}
In the first iteration of the outer loop, i==0.
Therefore in the inner loop j would go from 1 to n-i-1==n-1.
When j==(n-1), intArray[j+1] would throw ArrayIndexOutOfBoundsException.
On the first iteration of the outer loop of your bubbleSort method, when i is equal to zero, j is allowed to go up to n-i-1, inclusive, i.e. the last value of j is going to be n-1.
When this happens, inArray[j+1] will be out of bounds, because it would be equivalent to inArray[n]. The last valid index is n-1.
to fix this, make sure that the outer loop starts at i=1 instead of i=0.
I commented on the lines where you made a mistake
public static class BubbleSort { //you need static here
public static void main(String[] args) {
int intArray[] = new int[] { 5, 90, 35, 45, 150, 3 };
System.out.println("Array before Bubble Sort");
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
bubbleSort(intArray);
System.out.println("");
System.out.println("Array after Bubble Sort");
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " "); // you need space between the parenthesis so that results show up readable
}
}
private static void bubbleSort(int[] intArray) {
int n = intArray.length;
int hold = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < (n - i - 1); j++){ // j has to be equal to 0, or your first value in the array won't get compared, and -1 because of the array out of bounds error
if (intArray[j] > intArray[j + 1]){
hold = intArray[j];
intArray[j] = intArray[j + 1];
intArray[j + 1] = hold;
}
}
}
}
}
public class BubbleSort
{
public static void main (String[]args)
{
// create the array that we want to sort with buble sort alogorithm
int intArray[] = new int[] {5, 90, 35, 45, 150, 3};
//print the array before the bubble sort
System.out.println ("Array before Bubble Sort");
for (int i = 0 ; i intArray[j+1]) //swap the elements!
{
hold = intArray[j];
intArray[j] = intArray[j + 1];
intArray[j + 1] = hold;
}
}
}
}
}
Replace j < (n-i) with j < (n-i)-1.
Reason
In the last iteration, j will have a value equal to one less than the length of the array(ie it points to the last element). But when you compare elements with index j+1, you are pointing to an out of bound element. Thus the exception. Hope it helps.
(this is to answer your question about 3 not being the first value displayed)
code should go like this if you want in assenting order
you have missed for( int j=0; j<(n-i-1); j++
for (int i=0; i<n; i++) //loop trough array
{
for( int j=0; j<(n-i-1); j++) //loop allows variable j pass on for comparison
{
if ( intArray[j]> intArray[j+1]) // if current slot in array j is bigger than the next one
Related
I am trying to understand the SelectionSort for arrays.
If I understand it correctly, it compares the element[minimum] with the next elements element[i] and swaps positions if element[i] < element[minimum]. Then it repeats this with element[i + 1] until the list is sorted.
Now when I try it with the following code, I get an incorrect sort and can't figure out what I'm doing wrong.
public static void SelectionSort1(int[] list){
for (int i = 0; i < (list.length - 1); i++){
int min = i;
for (int j = i + 1; j<list.length; j++){
if(list[j] < list[min]){
min = j;
}
int smallernumber = list[i];
list[i] = list[min];
list[min] = smallernumber;
}
}
}
public static void main (String [] args){
int[] list = {5,4,2,1,3};
System.out.println("Before Sort" + Arrays.toString(list));
SelectionSort1(list);
System.out.println("After Sort " + Arrays.toString(list));
}
My output is:
Before Sort[5, 4, 2, 1, 3]
After Sort [2, 3, 1, 4, 5]
Can anyone point me in the right direction?
Your understanding is almost correct, it compares the element[minimum] with the next elements element[j] and if element[j] < element[minimum] then the minimum index is equal to j. Then it repeats until j reaches the end of the array. After it swaps the index at element[i] with element[minimum].
What this is doing is swapping element[i] with the smallest number to the right of index i. Then moving index i to the next spot. Repeating this gives you a sorted array.
TLDR:
Move the swapping outside of the second for loop. It should be:
public static void SelectionSort1(int[] list){
for (int i = 0; i < (list.length - 1); i++){
int min = i;
for (int j = i + 1; j<list.length; j++){
if(list[j] < list[min]){
min = j;
}
}
int smallernumber = list[i];
list[i] = list[min];
list[min] = smallernumber;
}
}
I have an array of objects in Java, and I am trying to pull one element to the top and shift the rest down by one.
Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0 and all elements from 0 to 5 will be shifted down by one.
This algorithm does not properly shift the elements:
Object temp = pool[position];
for (int i = 0; i < position; i++) {
array[i+1] = array[i];
}
array[0] = temp;
How do I do it correctly?
Logically it does not work and you should reverse your loop:
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
Alternatively you can use
System.arraycopy(array, 0, array, 1, position);
Assuming your array is {10,20,30,40,50,60,70,80,90,100}
What your loop does is:
Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}
Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}
What you should be doing is
Object temp = pool[position];
for (int i = (position - 1); i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
You can just use Collections.rotate(List<?> list, int distance)
Use Arrays.asList(array) to convert to List
more info at: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)
Instead of shifting by one position you can make this function more general using module like this.
int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;
for(int i=0; i<original.length;i++)
reordered[i] = original[(shift+i)%original.length];
Just for completeness: Stream solution since Java 8.
final String[] shiftedArray = Arrays.stream(array)
.skip(1)
.toArray(String[]::new);
I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.
Manipulating arrays in this way is error prone, as you've discovered. A better option may be to use a LinkedList in your situation. With a linked list, and all Java collections, array management is handled internally so you don't have to worry about moving elements around. With a LinkedList you just call remove and then addLast and the you're done.
Try this:
Object temp = pool[position];
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
Look here to see it working: http://www.ideone.com/5JfAg
Using array Copy
Generic solution for k times shift k=1 or k=3 etc
public void rotate(int[] nums, int k) {
// Step 1
// k > array length then we dont need to shift k times because when we shift
// array length times then the array will go back to intial position.
// so we can just do only k%array length times.
// change k = k% array.length;
if (k > nums.length) {
k = k % nums.length;
}
// Step 2;
// initialize temporary array with same length of input array.
// copy items from input array starting from array length -k as source till
// array end and place in new array starting from index 0;
int[] tempArray = new int[nums.length];
System.arraycopy(nums, nums.length - k, tempArray, 0, k);
// step3:
// loop and copy all the remaining elements till array length -k index and copy
// in result array starting from position k
for (int i = 0; i < nums.length - k; i++) {
tempArray[k + i] = nums[i];
}
// step 4 copy temp array to input array since our goal is to change input
// array.
System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
}
code
public void rotate(int[] nums, int k) {
if (k > nums.length) {
k = k % nums.length;
}
int[] tempArray = new int[nums.length];
System.arraycopy(nums, nums.length - k, tempArray, 0, k);
for (int i = 0; i < nums.length - k; i++) {
tempArray[k + i] = nums[i];
}
System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
}
In the first iteration of your loop, you overwrite the value in array[1]. You should go through the indicies in the reverse order.
static void pushZerosToEnd(int arr[])
{ int n = arr.length;
int count = 0; // Count of non-zero elements
// Traverse the array. If element encountered is non-zero, then
// replace the element at index 'count' with this element
for (int i = 0; i < n; i++){
if (arr[i] != 0)`enter code here`
// arr[count++] = arr[i]; // here count is incremented
swapNumbers(arr,count++,i);
}
for (int j = 0; j < n; j++){
System.out.print(arr[j]+",");
}
}
public static void swapNumbers(int [] arr, int pos1, int pos2){
int temp = arr[pos2];
arr[pos2] = arr[pos1];
arr[pos1] = temp;
}
Another variation if you have the array data as a Java-List
listOfStuff.add(
0,
listOfStuff.remove(listOfStuff.size() - 1) );
Just sharing another option I ran across for this, but I think the answer from #Murat Mustafin is the way to go with a list
public class Test1 {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5, 6 };
Test1 test = new Test1();
x = test.shiftArray(x, 2);
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public int[] pushFirstElementToLast(int[] x, int position) {
int temp = x[0];
for (int i = 0; i < x.length - 1; i++) {
x[i] = x[i + 1];
}
x[x.length - 1] = temp;
return x;
}
public int[] shiftArray(int[] x, int position) {
for (int i = position - 1; i >= 0; i--) {
x = pushFirstElementToLast(x, position);
}
return x;
}
}
A left rotation operation on an array of size n shifts each of the array's elements unit to the left, check this out!!!!!!
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]); //no. of elements in the array
int d = Integer.parseInt(nd[1]); //number of left rotations
int[] a = new int[n];
for(int i=0;i<n;i++){
a[i]=scanner.nextInt();
}
Solution s= new Solution();
//number of left rotations
for(int j=0;j<d;j++){
s.rotate(a,n);
}
//print the shifted array
for(int i:a){System.out.print(i+" ");}
}
//shift each elements to the left by one
public static void rotate(int a[],int n){
int temp=a[0];
for(int i=0;i<n;i++){
if(i<n-1){a[i]=a[i+1];}
else{a[i]=temp;}
}}
}
You can use the Below codes for shifting not rotating:
int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
int n = arr.length;
int d = 3;
Programm for shifting array of size n by d elements towards left:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {4,5,6,7,8,9,10,11,12,10,11,12}
public void shiftLeft(int []arr,int d,int n) {
for(int i=0;i<n-d;i++) {
arr[i] = arr[i+d];
}
}
Programm for shifting array of size n by d elements towards right:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {1,2,3,1,2,3,4,5,6,7,8,9}
public void shiftRight(int []arr,int d,int n) {
for(int i=n-1;i>=d;i--) {
arr[i] = arr[i-d];
}
}
import java.util.Scanner;
public class Shift {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int array[] = new int [5];
int array1[] = new int [5];
int i, temp;
for (i=0; i<5; i++) {
System.out.printf("Enter array[%d]: \n", i);
array[i] = input.nextInt(); //Taking input in the array
}
System.out.println("\nEntered datas are: \n");
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
}
temp = array[4]; //We declared the variable "temp" and put the last number of the array there...
System.out.println("\nAfter Shifting: \n");
for(i=3; i>=0; i--) {
array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
}
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array1[i]);
}
input.close();
}
}
Write a Java program to create an array of 20 integers, and then implement the process of shifting the array to right for two elements.
public class NewClass3 {
public static void main (String args[]){
int a [] = {1,2,};
int temp ;
for(int i = 0; i<a.length -1; i++){
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
for(int p : a)
System.out.print(p);
}
}
I am trying to write a static method that returns an integer, takes a 2-dimensional array of integers as a parameter and return the index of the row in the 2-d array (jagged arrays) that has the largest sum of all its elements. Something went wrong along the line and im still trying to figure out. Help please?
Here is the code:
public static int findMaxRow(int[][] maxRows){
newI= 0;
newJ= 0;
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
`` if( newI > newJ){
return newI;
else {
}
}
}
}
You never define the type for newI or newJ, that can be fixed by preceding their declaration with their intended type (i.e int). You also have two " ` " before your if statement, and your missing a closing bracket " } " before your else statement. But those are just syntactical errors. Once you fix those errors you're going to notice that your method is not returning the desired results.
Looking at your code, specifically the for loops.
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
// other stuff
}
}
Let's say that maxRows.length equals 3. That means the outer loop is going to run from 0 to 2, so newI will equal 3. Meanwhile for each iteration the outer loop makes, the inner loop iterates 3 times. So newJ will end up equalling 9. Which is not the right way to go about summing the elements of an array. A better way to go about it, is to iterate over the arrays in the outer loop and sum the elements in the inner loop, then make a comparison completing the outer loop. Like so:
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
Here is an example of what you're trying to accomplish.
public class RowSums {
public static void main(String[] args) {
int[][] test = { {1, 5, 7, 0, 9} , {2, 4, 5, 6, 7} , {9, 2, 0, 12, 8, 3} };
System.out.println(printRows(test));
System.out.println("The row with the largest sum is row "
+ findMaxRow(test));
}
public static int findMaxRow(int[][] maxRows){
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
}
public static String printRows(int[][] rows) {
StringBuilder s = new StringBuilder("Rows and their sums:\n");
int sum;
for(int x = 0; x < rows.length; x++) {
s.append("Row [" + x + "] = [ ");
sum = 0;
for(int y = 0; y < rows[x].length; y++) {
s.append(rows[x][y] + " ");
sum += rows[x][y];
}
s.append("]\n");
s.append("Row [" + x + "]'s sum is " + sum + "\n");
}
return s.toString();
}
}
Output:
Rows and their sums:
Row [0] = [ 1 5 7 0 9 ]
Row [0]'s sum is 22
Row [1] = [ 2 4 5 6 7 ]
Row [1]'s sum is 24
Row [2] = [ 9 2 0 12 8 3 ]
Row [2]'s sum is 34
The row with the largest sum is row 2
Modifying your program, the following example will return the index of the row that has the largest sum of elements in it.
Let us suppose our array to be passed is:
int [][] maxRows = {{1,2,3}, {1,2,3,4,5}, {9,9,9,9}, {1,2}};
passing this array in the method
public static int findMaxRow(int[][] maxRows){
int sum = Integer.MIN_VALUE;
int biggestIndex= 0;
for(int i = 0; i<maxRows.length; i++){
int temp = 0;
for(int ir : maxRows[i]){
temp+=ir;
}
if(temp>sum){
sum = temp;
biggestIndex = i;
}
}
return biggestIndex;
}
The above program will return the index of the inner array which has the largest sum of elements, in above case, it will return 2 .
Sorry am kind of lame at this. I've looked on here for a way to Bubble sort so that I can get an array to go from largest number to smallest. I've found some error in my current iteration of the sort, I can't seem to get the array to sort once it compares a smaller number to a bigger number. Here what I am using thus far.
//bubble sort
for(int i=0;i<size;i++)
{
for(int v=1;i<(size-i);i++)
{
if(arrInt[v-1]<arrInt[v])
{
temp = arrInt[v-1];
arrInt[v-1]=arrInt[v];
arrInt[v]=temp;
}
}
}
int n = arrInt.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int v = 1; v < (n - i); v++) {
if (arrInt[v - 1] < arrInt[v]) {
temp = arrInt[v - 1];
arrInt[v - 1] = arrInt[v];
arrInt[v] = temp;
}
}
}
Try this.
Update - Replaced j with v
The problem is the inner loop should be from 1 to n. Instead your inner loop stops early.
Also you are testing i in the inner loop condition, but you should be testing v.
Try this:
//bubble sort
for(int i=0;i<size;i++)
{
for(int v=1;v<size;v++)
{
if(arrInt[v-1]<arrInt[v])
{
temp = arrInt[v-1];
arrInt[v-1]=arrInt[v];
arrInt[v]=temp;
}
}
}
Bubble Sort Method for Descending Order
public static void BubbleSort( int[ ] arr){
int records=arr.length-1;
boolean notSorted= true; // first pass
while (notSorted) {
notSorted= false; //set flag to false awaiting a possible swap
for( int count=0; count < records; count++ ) {
if ( arr[count] < arr[count+1] ) { // change to > for ascending sort
arr[count]=arr[count]+arr[count+1];
arr[count+1]=arr[count]-arr[count+1];
arr[count]=arr[count]-arr[count+1];
notSorted= true; //Need to further check
}
}
}
}
In this method when array is sorted then it does not check further.
Usually I implement Bubble sort like this,
for(int i=0;i<size-1;i++) {
for(int v=0;v<(size-1-i);v++){
if(arrInt[v]<arrInt[v+1])
{
temp = arrInt[v];
arrInt[v]=arrInt[v+1];
arrInt[v+1]=temp;
}
}
}
You know what is the problem is, in your code??? Look at the inner loop, you are initializing v but checking and changing i. Must be a copy paste error.. :P
Hope it helped...
Here you go:
int x = 0;
for(int i = 0; i < array.length; i++)
for(int j = 0; j < array.length; j++)
if(array[i] > array[j + 1])
x = array[j + 1];
array[j + 1]= array[i];
array[i] = x;
x here is a temporary variable you only need for this operation.
here's a complete running program for you. Hope that keeps you motivated
package test;
public class BubbleSort {
private static int[] arr = new int[] { 1, 45, 65, 89, -98, 2, 75 };
public static void sortBubbleWay() {
int size = arr.length-1;
int temp = 0; // helps while swapping
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i; j++) {
if (arr[j] < arr[j+1]) { /* For decreasing order use < */
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
private static void showShortedArray() {
for (int elt : arr) {
System.out.println(elt);
}
}
public static void main(String args[]) {
sortBubbleWay();
showShortedArray();
}
}//end of class
I tried to make an implementation of bubble sort, but I am not sure whether it is correct or not. If you can give it a look and if it is a bubble sort and can be done in better way please don't be shy. Here is the code:
package Exercises;
import java.util.*;
public class BubbleSort_6_18
{
public static void main(String[] args)
{
Random generator = new Random();
int[] list = new int[11];
for(int i=0; i<list.length; i++)
{
list[i] = generator.nextInt(10);
}
System.out.println("Original Random array: ");
printArray(list);
bubbleSort(list);
System.out.println("\nAfter bubble sort: ");
printArray(list);
}
public static void bubbleSort(int[] list)
{
for(int i=0; i<list.length; i++)
{
for(int j=i + 1; j<list.length; j++)
{
if(list[i] > list[j])
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
public static void printArray(int[] list)
{
for(int i=0; i<list.length; i++)
{
System.out.print(list[i] + ", ");
}
}
}
private static int [] bublesort (int[] list , int length) {
boolean swap = true;
int temp;
while(swap){
swap = false;
for(int i = 0;i < list.length-1; i++){
if(list[i] > list[i+1]){
temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
swap = true;
}
}
}
return list;
}
Mohammod Hossain implementation is quite good but he does alot of unecessary iterations, sadly he didnt accept my edit and i can't comment due to reputations points so here is how it should look like:
public void sort(int[] array) {
int temp = 0;
boolean swap = true;
int range = array.length - 1;
while (swap) {
swap = false;
for (int i = 0; i < range; i++) {
if (array[i] > array[i + 1]) {
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swap = true;
}
}
range--;
}
}
This is the calssical implementation for bubble sort and it seems to be OK. There are several optimizations that can be done, but the overall idea is the same. Here are some ideas:
If there is an iteration of the outer cycle when no swap is performed in the inner cycle, then break, no use to continue
On each iteration of the outer cycle swap the direction of the inner one - do it once left to right and then do it once right to left(this helps avoid elements moving slowly towards the right end).
{
System.out.println("The Elments Before Sorting:");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
for(i=1;i<=a.length-1;i++)
{
for(j=0;j<=a.length-i-1;j++)
{
if((a[j])>(a[j+1]))
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
System.out.println("The Elements After Sorting:");
for(i=0;i<a.length;i++)
{
System.out.println(a[i]+"\t");
}
}
}
Short Answer: This is definitely NOT Bubble sort. It is a variant of Selection sort (a less efficient variant than the commonly known one).
It might be helpful to see a visualization of how they work on VisuAlgo
Why this is not bubble sort?
Because you loop over the array and compare each element to each other element on its right. if the right element is smaller you swap. Thus, at the end of the first outer loop iteration you will have the smallest element on the left most position and you have done N swaps in the worst case (think of a reverse-ordered array).
If you think about it, you did not really need to do all these swaps, you could have searched for the minimum value on the right then after you find it you swap. This is simply the idea of Selection sort, you select the min of remaining unsorted elements and put it in its correct position.
How does bubble sort look like then?
In bubble sort you always compare two adjacent elements and bubble the larger one to the right. At the end of the first iteration of the outer loop, you would have the largest element on the right-most position. The swap flag stops the outer loop when the array is already sorted.
void bubbleSort(int[] arr) {
boolean swap = true;
for(int i = arr.length - 1; i > 0 && swap; i--) {
swap = false;
// for the unsorted part of the array, bubble the largest element to the right.
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j+1]) {
// swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swap = true;
}
}
}
}
Yes it seems to be Bubble sort swapping the elements
Bubble sort
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
It will give in worst case O(n^2) and even if array is sorted.
I think you got the idea of bubble sort by looking at your code:
Bubble sort usually works like the following:
Assume aNumber is some random number:
for (int i = 0; i < aNumber; i++)
{
for(int j = 0; j < aNumber; j++)
//Doing something with i and j, usually running it as a loop for 2D array
//array[i][j] will give you a complete sort.
}
How bubble sort works is it iterates through every single possible spot of the array. i x j times
The down side to this is, it will take square the number of times to sort something. Not very efficient, but it does get the work done in the easiest way.
You can loop over the array until no more elements are swapped
When you put the element at the last position you know it's the largest, so you can recuce the inner loop by 1
A bubblesort version with while loops from my first undergraduate year ("the BlueJ era").
public static void bubbleSort()
{
int[] r = randomArrayDisplayer();
int i = r.length;
while(i!=0){
int j = 0;
while(j!=i-1){
if(r[j+1]<r[j]){
swap(r,j,j+1);
}
j++;
}
i--;
}
}
private static void swap(int[] r, int u, int v)
{
int value = r[u];
r[u] = r[v];
r[v] = value;
arrayDisplayer(r);
}
My advice is to display every step in order to be sure of the correct behaviour.
public class BubbleSort {
public static void main(String[] args) {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
BubbleSort client=new BubbleSort();
int[] result=client.bubbleSort(arr);
for(int i:result)
{
System.out.println(i);
}
}
public int[] bubbleSort(int[] arr)
{
int n=arr.length;
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
if(arr[j]>arr[j+1])
swap(arr,j,j+1);
}
return arr;
}
private int[] swap(int[] arr, int i, int j) {
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
return arr;
}
}
Above code is looks like implementation Selection sort , it's not a bubble sort.
Please find below code for bubble sort.
Class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort");
n = in.nextInt();
int array[] = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
for (c = 0; c < ( n - 1 ); c++) {
for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d+1]) /* For descending order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
System.out.println("Sorted list of numbers");
for (c = 0; c < n; c++)
System.out.println(array[c]);
}
}
/*
Implementation of Bubble sort using Java
*/
import java.util.Arrays;
import java.util.Scanner;
public class BubbleSort {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements of array");
int n = in.nextInt();
int []a = new int[n];
System.out.println("Enter the integer array");
for(int i=0; i<a.length; i++)
{
a[i]=in.nextInt();
}
System.out.println("UnSorted array: "+ Arrays.toString(a));
for(int i=0; i<n; i++)
{
for(int j=1; j<n; j++)
{
if(a[j-1]>a[j])
{
int temp = a[j-1];
a[j-1]=a[j];
a[j]=temp;
}
}
}
System.out.println("Sorted array: "+ Arrays.toString(a));
}
}
/*
****************************************
Time Complexity: O(n*n)
Space Complexity: O(1)
****************************************
*/
class BubbleSort {
public static void main(String[] args) {
int a[] = {5,4,3,2,1};
int length = a.length - 1;
for (int i = 0 ; i < length ; i++) {
for (int j = 0 ; j < length-i ; j++) {
if (a[j] > a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
}
for (int x : a) {
System.out.println(x);
}
}
}
int[] nums = new int[] { 6, 3, 2, 1, 7, 10, 9 };
for(int i = nums.Length-1; i>=0; i--)
for(int j = 0; j<i; j++)
{
int temp = 0;
if( nums[j] < nums[j + 1])
{
temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
package com.examplehub.sorts;
public class BubbleSort implements Sort {
/**
* BubbleSort algorithm implements.
*
* #param numbers the numbers to be sorted.
*/
public void sort(int[] numbers) {
for (int i = 0; i < numbers.length - 1; ++i) {
boolean swapped = false;
for (int j = 0; j < numbers.length - 1 - i; ++j) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
/**
* Generic BubbleSort algorithm implements.
*
* #param array the array to be sorted.
* #param <T> the class of the objects in the array.
*/
public <T extends Comparable<T>> void sort(T[] array) {
for (int i = 0; i < array.length - 1; ++i) {
boolean swapped = false;
for (int j = 0; j < array.length - 1 - i; ++j) {
if (array[j].compareTo(array[j + 1]) > 0) {
T temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
}
source from
function bubbleSort(arr,n) {
if (n == 1) // Base case
return;
// One pass of bubble sort. After
// this pass, the largest element
// is moved (or bubbled) to end. and count++
for (let i = 0; i <n-1; i++){
if (arr[i] > arr[i + 1])
{
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
// Largest element is fixed,
// recur for remaining array
console.log("Bubble sort Steps ", arr, " Bubble sort array length reduce every recusrion ", n);
bubbleSort(arr, n - 1);
}
let arr1 = [64, 3400, 251, 12, 220, 11, 125]
bubbleSort(arr1, arr1.length);
console.log("Sorted array : ", arr1);
Here's an implementation for the bubble sort algorithm using Stack:
static void bubbleSort(int[] elements) {
Stack<Integer> primaryStack = new Stack<>();
Stack<Integer> secondaryStack = new Stack<>();
int lastIndex = elements.length - 1;
for (int element : elements) {
primaryStack.push(element);
} // Now all the input elements are in primaryStack
// Do the bubble sorting
for (int i = 0; i < elements.length; i++) {
if (i % 2 == 0) sort(elements, i, primaryStack, secondaryStack, lastIndex);
else sort(elements, i, secondaryStack, primaryStack, lastIndex);
}
}
private static void sort(int[] elements, int i, Stack<Integer> stackA, Stack<Integer> stackB, int lastIndex) {
while (!stackA.isEmpty()) { // Move an element from stack A to stack B
int element = stackA.pop();
if (stackB.isEmpty() || element >= stackB.peek()) { // Don't swap, just push
stackB.push(element);
} else { // Swap, then push
int temp = stackB.pop();
stackB.push(element);
stackB.push(temp);
}
}
elements[lastIndex - i] = stackB.pop();
}