How use other written methods with present method - java

I wrote a program for this problem:
“Write a program that, given an array array[] of n numbers and another number x, determines whether or not there exist two elements in array whose sum is exactly x.”
Which is this:
boolean hasArrayTwoCandidates (int array[], int sum) {
int length = array.length;
quickSort(array, 0, length-1);
int first, last;
first = 0;
last = length-1;
while(first < last){
if( array[first] + array[last] == sum )
return true;
else if( array[first] + array[last] < sum )
first++;
else // array[i] + array[j] > sum
last--;
}
return false;
}
At first place, I don't know where should I put or add "quick sort" codes. I have this problem with other programs, as well; when I want to add written methods to the present one.
Should I create a "new class" under this "project" and put "quicksort" codes there?
Should I put them in this class? but how can I use it?
At second place, I don't know what should I write in my "main method"?
this is my quicksort codes:
public void sort(int[] values) {
if (values == null || values.length == 0){
return;
}
this.array = values;
length = values.length;
quickSort(this.array, 0, length - 1);
}
private void quickSort(int[] array, int low, int high) {
int i = low, j = high;
int pivot = array[low + (high-low)/2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
if (low < j)
quickSort(array, low, j);
if (i < high)
quickSort(array, i, high);
}
private void exchange(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
actually, I dont know what should I write in my "main method" to run this program?

For you Question you can do simply this kind of coding in main method:
public static void main(String[]args) {
int x = 20;
int[] arr = {2,5,4,10,12,5};
System.out.println(hasArrayTwoCandidates(arr,x));
}
make the methods static
static boolean hasArrayTwoCandidates (int array[], int sum)
But there are porblems in your coding:
private void exchange(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Here the array is not defined. you'll get an error. you have to pass the array too to the method make it as.
private void exchange(int i, int j,int[] array)
But since you are not necessary to do sorting. I recommend this.
static boolean hasArrayTwoCandidates (int array[], int sum) {
boolean flag = false;
for(int i=0;i<array.length-1;i++){
for(int j=i+1;j<array.length ;j++){
if(array[i]+array[j] == sum)
flag = true;
}
}
return flag;
}
this will get one element and check while adding other elements that it is true
Then the main method come same way.

you can put all those method in same class, make hasArrayTwoCandidates() static (Note that main method is static and a static method can have access only to static methods)
public static boolean hasArrayTwoCandidates (int array[], int sum) {
....
}
and in your main method you can test it like this :
public static void main(String[] args){
int[] arr = {2,5,12,5,2,7,15};
System.out.print(hasArrayTwoCandidates(arr, 27));
}

Answering your questions: you can write methods and call them within the same class, just write them with the static modifier:
private static <return_type> <methodName> (<type> param1, <type> param2) {
// Your code here
}
For a program like this, I don't get why you are thinking about sorting the array before checking the sum of 2 numbers within it, when you could do all at once. Check out this code, this may shine a light on you. It is straight-forward and only to see if it clarifies your logic.
import java.util.Random;
public class VerifySum {
public static void main(String[] args) {
Random rand = new Random();
int[] array = new int[10];
// Produce a random number from 10 to 20
int randomSum = rand.nextInt(11) + 10;
// Fill out the array with random integers from 0 to 10
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(11);
}
// Check all array indexes against each other
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == randomSum) {
System.out.println(array[i] + " + " + array[j] + " = " + randomSum);
}
}
}
// Print "x"
System.out.println("randomSum = " + randomSum);
// Print array for verification of the functionality
for (int i = 0; i < array.length; i++) {
System.out.println("array [" + i + "] = " + array[i]);
}
}
}
Sometimes making it simpler is more efficient. ;-)

Related

Getting error in implementation of heap sort

I'm trying to create and sort a heap using this array in Java. I keep getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 42
at HeapSort.exchange(HeapSort.java:28)
at HeapSort.Max_Heapify(HeapSort.java:22)
at HeapSort.Build_Heap at HeapSort.Sort(HeapSort.java:36)
at HeapSort.main(HeapSort.java:46)
I'm not sure where the error is coming from.
public class HeapSort {
public static int n;
public static int[] a;
public static int largest;
public static void Build_Heap(int[] a){
n = a.length-1;
for(int i = n/2; i >= 0; i--){
Max_Heapify(a,i);
}
}
public static void Max_Heapify(int[] a,int i){
int left = 2*i;
int right = 2*i +1;
if(left <= n && a[left] > a[i])
largest = left;
if(right <=n && a[right] > a[largest])
largest = right;
if(largest != i)
exchange (a[i],a[largest]);
Max_Heapify(a,largest);
}
private static void exchange(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
// TODO Auto-generated method stub
}
public static void Sort(int[] a0){
a = a0;
Build_Heap(a);
for(int i = n; i > 0; i--){
exchange(0,i);
n = n-1;
Max_Heapify(a,0);
}
}
public static void main(String[] args){
int[] a1 = {3,55,6,42,34,56,34};
Sort(a1);
for(int i = 0; i < a1.length; i++){
System.out.print(a1[i] + " ");
}
}
}
You are getting an error in exchange(). The parameters i and j for that method look like to be indexes of the array a. But, you are calling the method exchange(a[i],a[largest]) which is passing the value of from the array at indexes i and largest instead of passing the actual indexes i and largest to the method.
Try calling exchange like exchange(i,largest)
The exchange call (on line 22) in Max_Heapify() is given the values of the array at those locations instead of the locations (the indexes, i and largest) that can be anything, in this example, 42 which is larger than the array to be sorted length,

Java bubble sort

i'm trying to create a bubble sort but I there is something wrong with my code. The output is : 82345679. I would like it to be : 23456789.
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
int[] tab = {9,8,7,6,5,4,3,2};
int[] result = {9,8,7,6,5,4,3,2};
for (int i = 0; i < result.length; i++ ) {
if (i < result.length - 1 ) {
if (result[i] > result[i+1]) {
result = permute(result, i);
i = 0;
}
}
}
for (int i: result) {
System.out.print(i);
}
}
public static int[] permute (int[] tableau, int index) {
int temp;
temp = tableau[index];
tableau[index] = tableau[index+1];
tableau[index+1] = temp;
return tableau;
}
}
The issue is with the combination of i = 0 and i++ in the for loop. Whenever you go in the i = 0 branch, you end up restarting at 1 because of the i++. Resulting in always skipping the 8 after the first iteration where the 9 is moved to the end.
So, either restart at -1, or use a while loop and only increment in an else block. For example:
int i = 0;
while (i < result.length - 1) {
if (result[i] > result[i+1]) {
permute(result, i)
i = 0;
} else {
i++;
}
}
However, I would advise against the one-loop bubble sort, because the algorithm complexity is harder to see (it is still O(n^2), but with only one loop it can give the impression that it is O(n)).
You need two loops.
int swap;
for (int i = 0; i < ( result.length - 1 ); i++) {
for (int j = 0; j < result.length - 1; j++) {
if (result[j] > result[j+1]) {
swap = result[j];
result[j] = result[j+1];
result[j+1] = swap;
}
}
}
You need to have 2 loops in order to compare each number to the whole array..
example of bubble sorting
public static void bubbleSort(int[] numArray) {
int n = numArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numArray[j - 1] > numArray[j]) {
temp = numArray[j - 1];
numArray[j - 1] = numArray[j];
numArray[j] = temp;
}
}
}
}
Refer to this question
Sorting an Array of int using BubbleSort
Can be done with ONE loop (although it is not the usual way to present the bubble sort):
public static void main (String args[]) {
int[] tab = {9,8,7,6,5,4,3,2};
int i=1; // let's do the bubble sort again
while (i < tab.length) {
// loop invariant : t[0] <= t[1] .... <= t[i-1]
if (tab[i-1] < tab[i]) { // bubble here
swap(tab, i-1, i);
if (i>1) {
i = i-1; // one step to the left....
}
} else {
i = i +1; // one step to the right
}
}
for (int x: tab) {
System.out.print(x);
}
}
static void swap(int[] t, int i, int j) {
int x = t[i];
t[i] = t[j];
t[j] = x;
}

Selection Sort in Java, ways I can improve the code?

This is the code I have for my selection sort program, I want to know if there's any way of improving the code without using additional methods or classes.
public class Selection_Sort {
public static void main(String[] args) {
int arr[]={234,151,123,4,5342,76,48};
int min=0; int temp;
for(int i=0;i<=arr.length-1;i++){
min=i;
for (int k=i+1;k<arr.length;k++){
if(arr[k]<arr[i]){
temp=arr[i];
arr[i]=arr[k];
arr[k]=temp;
}
}
}
for (int j=0;j<=arr.length-1;j++)
System.out.println(arr[j]+" ");
}
}
public static void main(String[] args) {
int arr[]={234,151,123,4,5342,76,48};
int arrLength = arr.length;
for(int i=0;i<arrLength-1;i++){
int min=i;
for (int k=i+1;k<arrLength;k++){
if(arr[k]<arr[min]){
min = k;
}
}
if (i != min) {
int temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
for (int j=0;j<arrLength;j++) {
System.out.println(arr[j]+" ");
}
}
Looks like you are using the bubblesort algorithm which is very slow. If you want to improve your code, i would recommend to use an algorithm like ripplesort or quicksort.
Slight improvement should be like this :
int arrayLength = arr.length;
// Then use it in conditional statement of for loop.
So that it won't invoke length property of Array every time in loop. For small number of loops it doesn't impact much but it will help to reduce the time when loops are more or number of iteration of loop are more.
The value of the local variable min is not used
k <= arr.length-1
-->
k < arr.length
Use this
class Selection {
public static void main(String[] args) {
int arr[]={234,151,123,4,5342,76,48}; /* arr[0] to arr[n-1] is the array to sort */
int lowest, i, j;
for(i = 0 ; i < arr.length-1; i++) { /* advance the position through the entire array */
lowest = i; /* assume the min is the first element */
for(j = i+1 ; j < arr.length; j++) { /* if this element is less, then it is the new minimum */
if(arr[j] < arr[lowest]) {
lowest = j; /* found new minimum; remember its index */
}
}
if(lowest != i) { /* lowest is the index of the minimum element. Swap it with the current position */
int temp = arr[i];
arr[i] = arr[lowest];
arr[lowest] = temp;
}
}
for (int k = 0; k <= arr.length-1 ; k++) {
System.out.println(arr[k] + " ");
}
}
}
This is the selection sort algorithm you asked.
Here is original Selection sort implementation. The implementation in question in not using min to perform the swap operation.
public static void sort(int[] arr) {
int min=-1;
for (int i = 0; i < arr.length; i++) {
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min != i) {
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
public class JavaApplication55 {
public static void main(String[] args) {
int[] array ={234,435,567,768,123,456,789,789,5670,6789};
for(int j =0;j< array.length;j++){
for(int i =j+1;i < array.length;i++ ){
int temp;
if(array[j]>array[i]){
temp =array[j];
array[j] =array[i];
array[i] =temp;
}
else{}
}}
for(int k =0;k< array.length;k++){
System.out.println(array[k]);
}
}
enter code here
}

Searching a 2D Array

I have instantiated a 2D array of an editable number of rows and a set number of three columns.
It is randomly filled with 0's and 1's using the Random .nextInt(2) method.
After the array is filled, I want to be able to search the array and return the first occurrence of a 0.
How can I do this?
For example, if i had an array that looked something like this:
1 1 0
0 1 0
1 1 1
The first occurence would be at (0,3). I want to search the array horizontally and when it reaches the third column (the end), it will go to the next row.
Note: I originally tested the following section of code with a 2D array that was completely filled with 0's and when I manually inserted 1's in the array and then tried to search for the first occurence of a 0 it worked. However, the code doesn't work when the array is randomly filled..
public String findNextAvailable()
{
for (int i=0; i<seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
int k=0;
if (seatlist[0][0]==0)
{
nextavailable= seatchart[0][0];
break;
}
else
if(seatlist[k][j]==0)
{
nextavailable= seatchart[k][j];
break;
}
else
{ k++;
if(seatlist[k][j]==0)
{
nextavailable= seatchart[k][j];
break;
}
}
}
}
return nextavailable;
}
Thanks in advance!
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
return "Next available seat at position: [" + i + "][" + j + "]";
}
}
}
return "No seat available";
Although you might want to create a seat object instead that is easier to work with:
public class Seat {
private int row;
private int column;
public Seat(int row, int column){
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}
and replace the returning of a string with:
return new Seat(i,j);
well when you break in the inner loop, you still execute again the outer loop and you wind up replacing what you think is your final result by the next run of the outer loop. rather than use break, just return right there.
You need to return the positions of the first encountered 0, so why are you breaking out of the if statement, the outer loop will still run!
Simply create an integer array:
int[] pos=new array[2];
Change the return type:
public int[] findNextAvailable(){
In each of the if statements change the contents so that it reads:
pos[0]=i;
pos[1]=j;
return pos;
The end result will look something like this:
public int[] findNextAvailable()
{
int[] pos=new array[2];
for (int i=0; i<seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
if (seatlist[i][j]==0)
{
pos[0]=i;
pos[1]=j;
return pos;
}
}
}
//none found so return minus one.
pos[0]=-1;
pos[1]=-1;
return pos;
}
there are many different types of searches, some faster and some easier to do. Here's a program i made that has methods for all types of them. you will have to modify them a bit so it will search a 2d array but it shouldn't be too hard.
'
package linear_search;
import java.util.Arrays;
import java.util.Scanner;
public class Linear_search {
int[] array = {10,12,42,7,22,1,3,4,5,9};
int ans;
int num;
int min;
int max;
void start(){
arraySort(array);
dump(array);
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value to search:");
num = scan.nextInt();
ans = recursiveBinarySearch(array, 0, array.length-1);
if(ans == -1){
System.out.println("Your value was not found");
} else {
System.out.println("Your value was found at position " + ans);
}
}
void dump(int[] array){
for(int i = 0; i < array.length ; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
int linearsearch(int[] array){
for(int i = 0; i < array.length; i++){
if(array[i] == num){
return i;
}
}
return -1;
}
int binarysearch(int[] array){
min = 0;
max = array.length -1;
int mid = (min + max) / 2;
while(array[mid] != num){
if(num > array[mid]){
min = mid+1;
mid = (min + max) / 2;
}
if(num < array[mid]){
max = mid-1;
mid = (min + mid) / 2;
}
if(min == max && array[mid] != num){
return -1;
}
}
return mid;
}
int recursiveBinarySearch(int[] array, int min, int max){
int mid = (min + max) / 2;
if(array[mid] == num){
return mid;
}
if(min == max && array[mid] != num){
return -1;
}
if(num > array[mid]){
return recursiveBinarySearch(array, mid+1, max);
}
if(num < array[mid]){
return recursiveBinarySearch(array, min, mid-1);
}
return mid;
}
void arraySort(int[] a){
Arrays.sort(array);
}
public static void main(String[] args) {
Linear_search main = new Linear_search();
main.start();
}
}
'
you will just have to remove the scanner and hard code in "0" for the default value you should search for.

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