Java bubble sort - java

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

Related

Java set/setElementAt not setting the right value

I need to find all the permutations for a given n(user input) without backtracking.
What i tried is:
import java.util.Scanner;
import java.util.Vector;
class Main {
private static int n;
private static Vector<Vector<Integer>> permutations = new Vector<>();
private static void get_n() {
Scanner user = new Scanner(System.in);
System.out.print("n = ");
n = user.nextInt();
}
private static void display(Vector<Vector<Integer>> permutations) {
for (int i = 0; i < factorial(n) - 1; ++i) {
for (int j = 0; j < n; ++j) {
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
}
System.out.println();
}
}
private static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
private static int max(Vector<Integer> permutation) {
int max = permutation.elementAt(0);
for (int i = 1; i < permutation.size(); ++i)
if (permutation.elementAt(i) > max)
max = permutation.elementAt(i);
return max;
}
// CHECKS FOR ELEMENT COUNT AND 0 - (n-1) APPARITION
public static int validate_permutation(Vector<Integer> permutation) {
// GOOD NUMBER OF ELEMENTS
if (max(permutation) != permutation.size() - 1)
return 0;
// PROPER ELEMENTS APPEAR
for (int i = 0; i < permutation.size(); ++i)
if (!permutation.contains(i))
return 0;
return 1;
}
private static Vector<Integer> next_permutation(Vector<Integer> permutation) {
int i;
do {
i = 1;
// INCREMENT LAST ELEMENT
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
// IN A P(n-1) PERMUTATION FOUND n. "OVERFLOW"
while (permutation.elementAt(permutation.size() - i) == permutation.size()) {
// RESET CURRENT POSITION
permutation.set(permutation.size() - i, 0);
// INCREMENT THE NEXT ONE
++i;
permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1);
}
} while (validate_permutation(permutation) == 0);
// OUTPUT
System.out.print("output of next_permutation:\t\t");
for (int j = 0; j < permutation.size(); ++j)
System.out.print(permutation.elementAt(j) + " ");
System.out.println();
return permutation;
}
private static Vector<Vector<Integer>> permutations_of(int n) {
Vector<Vector<Integer>> permutations = new Vector<>();
// INITIALIZE PERMUTATION SET WITH 0
for (int i = 0; i < factorial(n); ++i) {
permutations.addElement(new Vector<>());
for(int j = 0; j < n; ++j)
permutations.elementAt(i).addElement(0);
}
for (int i = 0; i < n; ++i)
permutations.elementAt(0).set(i, i);
for (int i = 1; i < factorial(n); ++i) {
// ADD THE NEXT PERMUTATION TO THE SET
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
System.out.print("values set by permutations_of:\t");
for (int j = 0; j < permutations.elementAt(i).size(); ++j)
System.out.print(permutations.elementAt(i).elementAt(j) + " ");
System.out.println("\n");
}
System.out.print("\nFinal output of permutations_of:\n\n");
display(permutations);
return permutations;
}
public static void main(String[] args) {
get_n();
permutations.addAll(permutations_of(n));
}
}
Now, the problem is obvious when running the code. next_permutation outputs the correct permutations when called, the values are set correctly to the corresponding the vector of permutations, but the end result is a mass copy of the last permutation, which leads me to believe that every time a new permutation is outputted by next_permutation and set into the permutations vector, somehow that permutation is also copied over all of the other permutations. And I can't figure out why for the life of me.
I tried both set, setElementAt, and an implementation where I don't initialize the permutations vector fist, but add the permutations as they are outputted by next_permutation with add() and I hit the exact same problem. Is there some weird way in which Java handles memory? Or what would be the cause of this?
Thank you in advance!
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i);
This is literally setting the vector at permutations(i) to be the same object as permutations[i-1]. Not the same value - the exact same object. I think this the source of your problems. You instead need to copy the values in the vector.

How do you Bubble Sort Largest to Smallest

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

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
}

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

How can I find the smallest covering prefix of an array in Java?

Find the first covering prefix of a given array.
A non-empty zero-indexed array A consisting of N integers is given. The first covering
prefix of array A is the smallest integer P such that and such that every value that
occurs in array A also occurs in sequence.
For example, the first covering prefix of array A with
A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0],
A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in
array A.
My solution is
int ps ( int[] A )
{
int largestvalue=0;
int index=0;
for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}
for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}
But this only works for this input, this is not a generalized solution.
Got 100% with the below.
public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;
for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}
I would do this
int coveringPrefixIndex(final int[] arr) {
Map<Integer,Integer> indexes = new HashMap<Integer,Integer>();
// start from the back
for(int i = arr.length - 1; i >= 0; i--) {
indexes.put(arr[i],i);
}
// now find the highest value in the map
int highestIndex = 0;
for(Integer i : indexes.values()) {
if(highestIndex < i.intValue()) highestIndex = i.intValue();
}
return highestIndex;
}
Your question is from Alpha 2010 Start Challenge of Codility platform. And here is my solution which got score of 100. The idea is simple, I track an array of counters for the input array. Traversing the input array backwards, decrement the respective counter, if that counter becomes zero it means we have found the first covering prefix.
public static int solution(int[] A) {
int size = A.length;
int[] counters = new int[size];
for (int a : A)
counters[a]++;
for (int i = size - 1; i >= 0; i--) {
if (--counters[A[i]] == 0)
return i;
}
return 0;
}
here's my solution in C#:
public static int CoveringPrefix(int[] Array1)
{
// Step 1. Get length of Array1
int Array1Length = 0;
foreach (int i in Array1) Array1Length++;
// Step 2. Create a second array with the highest value of the first array as its length
int highestNum = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array1[i] > highestNum) highestNum = Array1[i];
}
highestNum++; // Make array compatible for our operation
int[] Array2 = new int[highestNum];
for (int i = 0; i < highestNum; i++) Array2[i] = 0; // Fill values with zeros
// Step 3. Final operation will determine unique values in Array1 and return the index of the highest unique value
int highestIndex = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array2[Array1[i]] < 1)
{
Array2[Array1[i]]++;
highestIndex = i;
}
}
return highestIndex;
}
100p
public static int ps(int[] a) {
Set<Integer> temp = new HashSet<Integer>();
int p = 0;
for (int i = 0; i < a.length; i++) {
if (temp.add(a[i])) {
p = i+1;
}
}
return p;
}
You can try this solution as well
import java.util.HashSet;
import java.util.Set;
class Solution {
public int ps ( int[] A ) {
Set set = new HashSet();
int index =-1;
for(int i=0;i<A.length;i++){
if(set.contains(A[i])){
if(index==-1)
index = i;
}else{
index = i;
set.add(A[i]);
}
}
return index;
}
}
Without using any Collection:
search the index of the first occurrence of each element,
the prefix is the maximum of that index. Do it backwards to finish early:
private static int prefix(int[] array) {
int max = -1;
int i = array.length - 1;
while (i > max) {
for (int j = 0; j <= i; j++) { // include i
if (array[i] == array[j]) {
if (j > max) {
max = j;
}
break;
}
}
i--;
}
return max;
}
// TEST
private static void test(int... array) {
int prefix = prefix(array);
int[] segment = Arrays.copyOf(array, prefix+1);
System.out.printf("%s = %d = %s%n", Arrays.toString(array), prefix, Arrays.toString(segment));
}
public static void main(String[] args) {
test(2, 2, 1, 0, 1);
test(2, 2, 1, 0, 4);
test(2, 0, 1, 0, 1, 2);
test(1, 1, 1);
test(1, 2, 3);
test(4);
test(); // empty array
}
This is what I tried first. I got 24%
public int ps ( int[] A ) {
int n = A.length, i = 0, r = 0,j = 0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
if ((long) A[i] == (long) A[j]) {
r += 1;
}
if (r == n) return i;
}
}
return -1;
}
//method must be public for codility to access
public int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);
int index= A[0];
for (int i = 0; i < A.length; i++) {
if( set.contains(A[i])) continue;
index = i;
set.add(A[i]);
}
return index;
}
this got 100%, however detected time was O(N * log N) due to the HashSet.
your solutions without hashsets i don't really follow...
shortest code possible in java:
public static int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);//avoid resizing
int index= -1; //value does not matter;
for (int i = 0; i < A.length; i++)
if( !set.contains(A[i])) set.add(A[index = i]); //assignment + eval
return index;
}
I got 100% with this one:
public int solution (int A[]){
int index = -1;
boolean found[] = new boolean[A.length];
for (int i = 0; i < A.length; i++)
if (!found [A[i]] ){
index = i;
found [A[i]] = true;
}
return index;
}
I used a boolean array which keeps track of the read elements.
This is what I did in Java to achieve 100% correctness and 81% performance, using a list to store and compare the values with.
It wasn't quick enough to pass random_n_log_100000 random_n_10000 or random_n_100000 tests, but it is a correct answer.
public int solution(int[] A) {
int N = A.length;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<N; i++){
if(!temp.contains(A[i])){
temp.add(A[i]);
}
}
for(int j=0; j<N; j++){
if(temp.contains(A[j])){
temp.remove((Object)A[j]);
}
if(temp.isEmpty()){
return j;
}
}
return -1;
}
Correctness and Performance: 100%:
import java.util.HashMap;
class Solution {
public int solution(int[] inputArray)
{
int covering;
int[] A = inputArray;
int N = A.length;
HashMap<Integer, Integer> map = new HashMap<>();
covering = 0;
for (int i = 0; i < N; i++)
{
if (map.get(A[i]) == null)
{
map.put(A[i], A[i]);
covering = i;
}
}
return covering;
}
}
Here is my Objective-C Solution to PrefixSet from Codility. 100% correctness and performance.
What can be changed to make it even more efficient? (without out using c code).
HOW IT WORKS:
Everytime I come across a number in the array I check to see if I have added it to the dictionary yet.
If it is in the dictionary then I know it is not a new number so not important in relation to the problem. If it is a new number that we haven't come across already, then I need to update the indexOftheLastPrefix to this array position and add it to the dictionary as a key.
It only used one for loop so takes just one pass. Objective-c code is quiet heavy so would like to hear of any tweaks to make this go faster. It did get 100% for performance though.
int solution(NSMutableArray *A)
{
NSUInteger arraySize = [A count];
NSUInteger indexOflastPrefix=0;
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<arraySize; i++)
{
if ([myDict objectForKey:[[A objectAtIndex:i]stringValue]])
{
}
else
{
[myDict setValue:#"YES" forKey:[[A objectAtIndex:i]stringValue]];
indexOflastPrefix = i;
}
}
return indexOflastPrefix;
}
int solution(vector &A) {
// write your code in C++11 (g++ 4.8.2)
int max = 0, min = -1;
int maxindex =0,minindex = 0;
min = max =A[0];
for(unsigned int i=1;i<A.size();i++)
{
if(max < A[i] )
{
max = A[i];
maxindex =i;
}
if(min > A[i])
{
min =A[i];
minindex = i;
}
}
if(maxindex > minindex)
return maxindex;
else
return minindex;
}
fwiw: Also gets 100% on codility and it's easy to understand with only one HashMap
public static int solution(int[] A) {
// write your code in Java SE 8
int firstCoveringPrefix = 0;
//HashMap stores unique keys
HashMap hm = new HashMap();
for(int i = 0; i < A.length; i++){
if(!hm.containsKey(A[i])){
hm.put( A[i] , i );
firstCoveringPrefix = i;
}
}
return firstCoveringPrefix;
}
I was looking for the this answer in JavaScript but didn't find it so I convert the Java answer to javascript and got 93%
function solution(A) {
result=0;
temp = [];
for(i=0;i<A.length;i++){
if (!temp.includes(A[i])){
temp.push(A[i]);
result=i;
}
}
return result;
}
// you can also use imports, for example:
import java.util.*;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> s = new HashSet<Integer>();
int index = 0;
for (int i = 0; i < A.length; i++) {
if (!s.contains(A[i])) {
s.add(A[i]);
index = i;
}
}
return index;
}
}

Categories