Bucket Sort Algorithm Code Issues - java

I need to implement the following in java.
Input: an array of integers
Output: Rearrange the array to have the following:
Suppose the first element in the original array has the value x
In the new array, suppose that x is in position I, that is data[I] = x. Then, data[j] <= x for all x and for all j > I. This means that all the values to the "left" of x are less than or equal to x and all the values to the "right" are larger than x.
An example is as follows: Suppose the array has the elements in this initial order: 4,3,9,2,7,6,5. After applying your algorithm, you should get: 3,2,4,5,9,7,6. That is, the leftmost element, 4, is positioned in the resulting array so that all elements less than 4 (2 and 3) are to its left (in no particular order), and all elements larger than 4 are to its right (in no particular order).
There is no space requirement for the algorithm, only that the problem is solved in O(n) time.
I have implemented a bucket sort, but am having some difficulties with the code.
public class Problem4
{
public static void partition(int[] A)
{
int x = A[0];
int l = A.length;
int[] bucket = int [];
for(int i=0; i<bucket.length; i++){
bucket[i]=0;
}
for (int i=0; i<l; i++){
bucket[x[i]]++;
}
int outPos=0;
for(int i=0; i<bucket.length; i++){
for(int j=0; j<bucket[i]; j++){
x[outPos++]=i;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = {4,3,9,2,7,6,5};
System.out.println("Before partition:");
for(int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
partition(A);
System.out.println("After partition:");
System.out.println("Before partition:");
for(int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
}
}
The lines:
int[] bucket = int[],
bucket[x[i]]++;, and
x[outpost++] = i;
are causing me troubles. I am getting the error
The type of expression must be an array type but is resolved to an int.
The problem stems from that first line where I am trying to create a new array called bucket. I would appreciate any suggestions! Thanks!

I don't think you need to resort to a bucket sort. Instead you can simply walk through the array, placing elements that are less than the split value at the front and elements that are greater at the back. We can use two variables, front and back to keep track of the insert position at the front and back of the array. Starting at position 1 in the array, if the value is less than the split value we place at front and increment front and the current index. If the value is greater we swap it with the value at back and decrement back, but we keep the current index.
Here's some code to illustrate:
public static void main(String[] args)
{
int[] A = {4,3,9,2,7,6,5};
sort(A);
System.out.println(Arrays.toString(A));
}
public static void sort(int[] arr)
{
int split = arr[0];
int front = 0;
int back = arr.length-1;
for(int i=1; front != back; )
{
if(arr[i] <= split)
{
arr[front] = arr[i];
front += 1;
i++;
}
else
{
swap(arr, i, back);
back -= 1;
}
}
arr[front] = split;
}
public static void swap(int[] arr, int i, int j)
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
Output:
[3, 2, 4, 7, 6, 5, 9]

Another approach you can use is to use the standard partition algorithm of QuickSort.
I have modified your code and the following code
public class Problem4
{
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
public static int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = {4,3,9,2,7,6,5};
System.out.println("Before partition:");
for(int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
// swap and call the standard partition algo of QuickSort
// on last element pivot. swap arr[low] and arr[high]
int low = 0;
int high = A.length-1;
int temp = A[low];
A[low] = A[high];
A[high] = temp;
partition(A, low, high);
System.out.println("\nAfter partition:");
for(int i = 0; i < A.length; i++)
{
System.out.print(A[i] + " ");
}
}
}
Outputs
Before partition:
4 3 9 2 7 6 5
After partition:
3 2 4 5 7 6 9
Hope it helps!

Related

How to shift element an int left in an array then adding a number to the end? [duplicate]

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);
}
}

Recursive Selection Sort in Java

I need to implement this algorithm creating a new ArrayList object at each recursive call.
My starting Array contains integers in this order"20, 40 ,10, 30 ,50 ,5" , after sorting it I have 5,5,5,5,5,5. I think that the problem is in the recursive call and in the last for cicle of the SelectionSort because removing the last for I notice that the the first element is sorted correctly.
import java.util.*;
public class SelectionSort {
//var
public ArrayList<Integer> arr ;
//constructor
public SelectionSort(ArrayList<Integer> arr){
this.arr = arr;
}
public ArrayList<Integer> getarraylist() {
return arr;
}
public void sort(){
//position of the last sorted element
int minimum =0;
if (arr.size() <=0 ) return;
for ( int j = 1; j < arr.size()-1; j++ ) {
if (arr.get(j) < arr.get(0) ) {
minimum = j;
//swap element 0 and minimum
int temp = arr.get(0);
arr.set(0, arr.get(minimum));
arr.set(minimum, temp);
}
}
//recursive call, new array without first element (already sorted)
ArrayList<Integer> arr2 = new ArrayList<>(arr.subList(1,arr.size()));
SelectionSort s2 = new SelectionSort(arr2);
s2.sort();
for(int i=0;i<s2.getarraylist().size();i++) {
arr.set(i, s2.getarraylist().get(i));
}
}
Driver class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer (Arrays.asList(20,40,10,30,50,5));
System.out.println("\n ARRAY ELEMENTS \n ");
for (int i: arr) {
System.out.println(i);
}
System.out.println("\n SORTED ELEMENTS \n ");
SelectionSort s = new SelectionSort(arr);
s.sort();
for (int i: s.getarraylist()) {
System.out.println(i);
}
}
}
You have actually two bugs in your algorithm that, together, lead to the observed output.
The first bug is within the for-loop that determines the minimal element:
for ( int j = 1; j < arr.size()-1; j++ ) { ...
You terminate one element too early, i.e. the last element is never considered. Thus, after the first iteration, the 5 is the last element in your ArrayList. In fact, it is the last element in every of your ArrayLists. The fix is to not subtract 1 in the for-condition:
for ( int j = 1; j < arr.size(); j++ ) { ...
The second bug is in your last for-loop where you copy the values from index i of s2 to index i of arr. You neglect the fact that s2 is one element shorter than arr. Thus, the only element not overriden is the last element. The fix is to get the i-th element from s2, but write it at the i + 1-th index of arr:
arr.set(i + 1, s2.getarraylist().get(i));
Now let us take look at how those two bugs lead to the observed output. Since
the last element in your ArrayList is never overridden and
the last element is always the same,
all elements have the same value (in your test case: 5).
Some remarks on your code:
the variable minimum is superfluous and can be replaced with j.
If you replace all occurences of ArrayList in SelectionSort with List, you can actually simplify the last part of your code to:
// remove the line declaring arr2, it is no longer needed
SelectionSort s2 = new SelectionSort(arr.subList(1, arr.size()));
s2.sort();
// last for-loop not needed anymore, method ends here
This is possible because ArrayList#subList(...) states that "The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa."
You should take a little bit more care wrt. indentation.
You have some minor inconsistencies in your coding style. For example, sometimes you write a blank after ( or before a ) or {, sometimes you do not. See what you like more and use it uniformly.
In Java, variable-, parameter- and methodnames should be written in camelCase (getarraylist() -> getArrayList())
With your last loop:
for(int i=0;i<s2.getarraylist().size();i++) {
arr.set(i, s2.getarraylist().get(i));
}
This overrides every element with the same number. (Why you got all 5's as your result) This is because you only iterate to the second to last element (arr.size()-1). Then you copy the elements in the line:
ArrayList<Integer> arr2 = new ArrayList<>(arr.subList(1,arr.size()));
Eventually you are only copying the last element over (5) and then copying this to the final ArrayList arr.
Also you create another SelectionSort object every time you call the sort method. This is not good.
Here is the code I wrote:
public void sort(List<Integer> list){
//position of the last ordered element
int minimum =0;
if (list.size() <=0 ) return;
for ( int j = 1; j < list.size(); j++ ) {
if (list.get(j) < list.get(0) ) {
minimum = j;
//swap element 0 and minimum
int temp = list.get(0);
list.set(0, list.get(minimum));
list.set(minimum, temp);
}
}
sort(list.subList(1,list.size()));
}
I changed it to accept an argument of List<Integer> (Because the subList() method returns a List) and then got rid of the last loop and where you created new objects.
Also youll have to change
s.sort();
to:
s.sort(s.getarraylist());
Output:
ARRAY ELEMENTS
20
40
10
30
50
5
SORTED ELEMENTS
5
10
20
30
40
50
Im not sure I understand the question, but I created a recursive (and iterative) selectionSort and InsertionSort just for fun, hope it helps.
public class Sorts {
public static void swap(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void selectionSortItr(Comparable[] a, int n) {
for (int i = 0; i < n - 1; i++) {
int f = i;
for (int j = i + 1; j < n; j++) {
if (a[j].compareTo(a[f]) < 0)
f = j;
}
swap(a, i, f);
}
}
public static int select(Comparable[] a, int n, int j, int f) {
if (j >= n)
return f;
if (a[j].compareTo(a[f]) < 0)
f = j;
return select(a, n, j + 1, f);
}
public static void selectionSort(Comparable[] a, int n, int i) {
if (i < n - 1) {
swap(a, i, select(a, n, i + 1, i));
selectionSort(a, n, i + 1);
}
}
public static void insertionSortItr(Comparable[] a) {
for (int i = 1; i < a.length; i++) {
int j;
Comparable cur = a[i];
for (j = i; j > 0 && cur.compareTo(a[j - 1]) < 0; j--) {
a[j] = a[j - 1];
}
a[j] = cur;
}
}
public static void insertionSortInner(Comparable[] a, Comparable cur, int j) {
if (j > 0 && cur.compareTo(a[j - 1]) < 0) {
a[j] = a[j - 1];
insertionSortInner(a, cur, j - 1);
} else {
a[j] = cur;
}
}
public static void insertionSort(Comparable[] a, int i, int n) {
if (i < n) {
insertionSortInner(a, a[i], i);
insertionSort(a, i + 1, n);
}
}
public static void main(String[] args) {
Integer[] a = new Integer[10];
for (int i = 0; i < 10; i++)
a[i] = (int) (Math.random()*100);
selectionSort(a, 10, 0);
for (int i = 0; i < 10; i++)
System.out.println(a[i]);
}
}

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?

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

BubbleSort Implementation

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();
}

Categories