i have array values as like
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
suppose if i pass value "5" to tat array, it should be ordered as like
{"5","6","7","8","9","10",1","2","3","4"};...
how to do?plz anyone help?
thank u
What you need is called rotation. You can use Collections.rotate() method. Convert the array to a list and pass it to the method. This will rotate the array in place since the list is backed by the array:
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
Collections.rotate(Arrays.asList(value), 5);
The above code will rotate the array by a distance of 5. The resulting value array:
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
Your question has two interpretations:
Rotate 5 steps, or
rotate the array so that 5 is the first element (regardless of where it is in the array).
Here is a solution for both alternatives:
import java.util.Arrays;
public class Test {
public static String[] rotateArray(String[] arr, int n) {
String[] rotated = new String[arr.length];
System.arraycopy(arr, n-1, rotated, 0, arr.length-n+1);
System.arraycopy(arr, 0, rotated, arr.length-n+1, n-1);
return rotated;
}
public static String[] rotateArrayTo(String[] arr, String head) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(head))
return rotateArray(arr, i + 1);
throw new IllegalArgumentException("Could not find " + head);
}
public static void main(String[] args) {
String[] value = {"1","2","3","4","5","6","7","8","9","10"};
// Rotate so that it starts at 5:th element
value = rotateArray(value, 5);
System.out.println(Arrays.toString(value));
// Rotate so that it starts with element "7"
value = rotateArrayTo(value, "7");
System.out.println(Arrays.toString(value));
}
}
Output:
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4]
[7, 8, 9, 10, 1, 2, 3, 4, 5, 6]
(ideone.com link)
first find the index of the entered value from the array..
and then in a loop move from the index to the final position.. and store these values in a new array.
after that, in the same result array, store the values from index 0 to the index of the entered value - 1.
You really don't need to store the values in a different array. Just find the index [say idx] of the value passed. And then start a loop from the start of the array and swap the values starting from idx.
For example -
idx = [some-value]
while [idx < arr.length]
temp = arr[i]
arr[i] = arr[idx]
arr[idx] = t
idx += 1
i += 1
Update:
I stand corrected by #aioobe. I simply worked out something for the 5th index - my bad. Here's something that works, if in case, you want to stay away from library functions -
private void slideLeft(String[] arr)
{
String t = arr[arr.length - 1];
String temp = null;
int next = -1;
for (int i = arr.length - 1; i >= 0; i--)
{
next = ( i == 0 ) ? arr.length - 1 : i - 1;
temp = arr[next];
arr[next] = t;
t = temp;
}
}
you'll need to call this method the number of times you need to shift the array members.
note: O(n^2) alert. not suitable for large shifts/arrays.
Related
I am relatively new to coding and I am starting a review of leetcode, and floundered on a question...looking at the 3ms-runtime solution leetcode supplied I am confused about the function of the 4th line in method findDisappearedNumbers.
My assumption is that for the 0 index running 'arr[nums[i] - 1]++' would assign 4 to arr[0], but it assigns 1. Can someone help me understand what is happening?
The result of running this code is: [1, 2, 2, 1, 0, 0, 1, 1]
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class FindAllNumbersDisappearedInAnArray {
public static void main(String[] args) {
int[] arr = new int[]{4,3,2,7,8,2,3,1};
/*System.out.println(findDisappearedNumbers(arr));*/
System.out.println(Arrays.toString(findDisappearedNumbers(arr))); //user added for examing code
}
public static int[] /*List<Integer>*/ findDisappearedNumbers(int[] nums) { //int[] was user added for examing code
List<Integer> list = new ArrayList<>();
int[] arr = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
arr[nums[i] - 1]++; //What is happening here?
}
for(int i = 0; i < nums.length; i++) {
if(arr[i] == 0) {
list.add(i+1);
}
}
/*return list;*/
return arr; //user added for examing code
}
}
(The question was:
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.)
In the expression arr[nums[i] - 1]++;, nums[i] - 1 determines the index of a value in arr[], not the value which should be wirtten into it. Than the found value is incremented by one, because of ++.
Knowing that the default value of an int is 0, so when arr[] is initialized it contains only zeros, we can see, that after the first iteration of the first for loop arr[] is [0, 0, 0, 1, 0, 0, 0, 0]. We see a 1 on the 4.th (starting from 1) position of arr[], which means that one 4 has been found in nums[].
If you add System.out.println(Arrays.toString(arr) after the first for loop you will see following output: [1, 2, 2, 1, 0, 0, 1, 1]. According to the logic described above, it means, that nums[] contains one 1, two 2s, two 3s, one 4, no 5, no 6, one 7 and one 8.
For some reason, my solution is not complete. I got 80/100 from hidden spec tests.
What's wrong with my solution? There is probably a certain use case that I'm not thinking of.
How would space/time complexity change using an ArrayList instead of an array?
Is there a better way to tackle this problem?
My current solution handles:
an empty input array
negative/positive integer values in the input array
duplicates in the input array
sorted/unsorted input array
Instructions:
Write a Java method removeLastOccurrence(int x, int[] arr), which removes the last occurrence of a given integer element x from a given array of integer elements arr.
The method should return a new array containing all elements in the given array arr except for the last occurrence of element x. The remaining elements should appear in the same order in the input and the returned arrays.
The code on the right shows you a code framework in which the implementation of one static method is still missing. Provide this implementation and check that it is correct by either writing more tests yourself or using the provided tests and specification tests.
My code:
class RemoveLastOccurrenceArray {
/**
* Takes the array and the last occurring element x,
* shifting the rest of the elements left. I.e.
* [1, 4, 7, 9], with x=7 would result in:
* [1, 4, 9].
*
* #param x the entry to remove from the array
* #param arr to remove an entry from
* #return the updated array, without the last occurrence of x
*/
public static int[] removeLastOccurrence(int x, int[] arr) {
// if arr == null return null;
if (arr == null || arr.length == 0) return arr;
// return a new array which will be size arr.legnth-1
int[] res = new int[arr.length - 1];
// introduce an int tracker which keep tracks of the index of the last occurrence of x
int last_index = -1;
// traverse through the array to get the index of the last occurrence
for (int i = 0; i < arr.length; i++) if (arr[i] == x) last_index = i;
int i = 0, j = 0;
// copying elements of array from the old one to the new one except last_index
while (i < arr.length) {
if (i == last_index) {
if (i++ < res.length) {
res[j++] = arr[i++];
}
} else res[j++] = arr[i++];
}
// if we pass in x which is not in the array just return the original array
if (last_index == -1) return arr;
// are there duplicates in the array? - WORKS
// does the array have negative numbers? - WORKS
// Is the array sorted/unsorted - WORKS
return res;
}
}
Passing Unit Tests
import static org.junit.Assert.*;
import org.junit.*;
public class RemoveLastOccurrenceArrayTest {
#Test
public void testRemoveArray_Empty() {
int[] array = new int[0];
assertEquals(0, RemoveLastOccurrenceArray.removeLastOccurrence(5, array).length);
}
#Test
public void testFirstSimple() {
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] result = {2, 3, 4, 5, 6, 7, 8, 9, 10};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(1, input));
}
#Test
public void testLastSimple() {
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] result = {1, 2, 3, 4, 5, 6, 7, 8, 9};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(10, input));
}
#Test
public void testPositiveInMiddleDuplicate() {
int[] input = {1, 2, 3, 3, 4, 5};
int[] result = {1, 2, 3, 4, 5};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(3, input));
}
#Test
public void testNegativeFirst() {
int[] input = {-3, -1, 2, -3, 3, 4, 5, 0};
int[] result = {-3, -1, 2, 3, 4, 5, 0};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(-3, input));
}
#Test
public void testLasttoRemove() {
int[] input = {1, 4, 7, 9};
int[] result = {1, 4, 7};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(9, input));
}
}
Why not try iterating backwards?
for(int i = arr.length; i => 0; i--)
{
if (arr[i] == x)
{
return ArrayUtils.remove(arr, i)
}
}
Then, after you find the index, you can use the Apache Commons ArrayUtils remove command to remove the item at the
This is the answer thank you very much!
Also, if there is no x to find, yours crashes ... mine doesn't. Maybe that's where the twenty marks went?
I was already checking for this but too late in my code. So I just had to move
if (last_index == -1) return arr; before the while loop, and I got 100/100 scores.
Would your prof prefer this? Just another way, and I don't think any more efficient than your answer. But maybe they like to see the java classes used ...
Does your prof not tell you where you lost marks? You can't improve if they don't tell you what they were expecting for full marks. But here was another way ... again, no better in my opinion, and not worth twenty more marks. I'll just post it, because it is 'another way.'
public int[] removeLastOccurrence2(int x, int[] arr) {
// if arr == null return null;
if (arr == null || arr.length == 0) return arr;
// Fill an ArrayList with your initial array ...
java.util.List list = new java.util.ArrayList(arr.length);
for (int i=0; i<arr.length; i++) {
list.add(arr[i]);
}
int[] res;
// Now ... use ArrayList methods to do the work.
// Also, if there is no x to find, yours crashes ... mine doesn't.
// Maybe that's where the twenty marks went?
if ( list.lastIndexOf(x) != -1 ) { // This screens for no x found at all ...
list.remove( list.lastIndexOf(x) ); // Done!
// Make a new array to return.
res = new int[list.size()];
for (int i=0; i<list.size(); i++) {
res[i] = (int) list.get(i);
}
} else {
// No 'x' found, so just return the original array.
res = arr;
}
return res;
}
How about reverse(), remove(), reverse()? Sorry if this is already mentioned in here somewhere and I missed it.
I have an array that contains the total number of lines in 3 files. Example: [3,4,5]. I would like to produce a sequence of numbers that count that array down to zero in a methodical way giving me every combination of lines in the three files. This example uses 3 files/length-3 array, but the algorithm should be able to work an array with any arbitrary length.
For the example above, the solution would look like:
[3,4,5] (line 3 from file 1, line 4 from file 2, line 5 from file 3)
[3,4,4]
[3,4,3]
[3,4,2]
[3,4,1]
[3,4,0]
[3,3,5]
[3,3,4]
[3,3,3]
[3,3,2]
and so on...
My first attempt at producing an algorithm for this recursively decrements a position in the array, and when that position reaches zero - decrements the position before it. However I'm not able to keep the decrementing going for farther than the last two positions.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FilePositionGenerator {
public static void main(String[] args) {
int[] starterArray = {2, 2, 2};
int[] counters = starterArray.clone();
List<Integer> results = new ArrayList<Integer>();
FilePositionGenerator f = new FilePositionGenerator();
f.generateFilePositions(starterArray, counters, (starterArray.length - 1), results);
}//end main
void generateFilePositions(int[] originalArray, int[] modifiedArray, int counterPosition, List<Integer> results) {
if (modifiedArray[counterPosition] == 0 && counterPosition > 0) {
modifiedArray[counterPosition] = originalArray[counterPosition];
counterPosition = counterPosition - 1;
} else {
modifiedArray[counterPosition] = modifiedArray[counterPosition] - 1;
System.out.println(Arrays.toString(modifiedArray));
generateFilePositions(originalArray, modifiedArray, counterPosition, results);
}
}
}
I understand that to deal with a variable length array, the algorithm must be recursive, but I'm having trouble thinking it through. So I decided to try a different approach.
My second attempt at producing an algorithm uses a dual pointer method that keeps a pointer on the current countdown position[the rightmost position], and a pointer to the next non-rightmost position(pivotPointer) that will be decremented when the rightmost position reaches zero. Like so:
import java.util.Arrays;
class DualPointer {
public static void main(String[] args) {
int[] counters = {2, 2, 2}; // initialize the problem set
int[] original = {2, 2, 2}; // clone a copy to reset the problem array
int[] stopConditionArray = {0, 0, 0}; // initialize an object to show what the stopCondition should be
int pivotLocation = counters.length - 1; // pointer that starts at the right, and moves left
int counterLocation = counters.length - 1; // pointer that always points to the rightmost position
boolean stopCondition = false;
System.out.println(Arrays.toString(counters));
while (stopCondition == false) {
if (pivotLocation >= 0 && counterLocation >= 0 && counters[counterLocation] > 0) {
// decrement the rightmost position
counters[counterLocation] = counters[counterLocation] - 1;
System.out.println(Arrays.toString(counters));
} else if (pivotLocation >= 0 && counters[counterLocation] <= 0) {
// the rightmost position has reached zero, so check the pivotPointer
// and decrement if necessary, or move pointer to the left
if (counters[pivotLocation] == 0) {
counters[pivotLocation] = original[pivotLocation];
pivotLocation--;
}
counters[pivotLocation] = counters[pivotLocation] - 1;
counters[counterLocation] = original[counterLocation]; // reset the rightmost position
System.out.println(Arrays.toString(counters));
} else if (Arrays.equals(counters, stopConditionArray)) {
// check if we have reached the solution
stopCondition = true;
} else {
// emergency breakout of infinite loop
stopCondition = true;
}
}
}
}
Upon running, you can see 2 obvious problems:
[2, 2, 2]
[2, 2, 1]
[2, 2, 0]
[2, 1, 2]
[2, 1, 1]
[2, 1, 0]
[2, 0, 2]
[2, 0, 1]
[2, 0, 0]
[1, 2, 2]
[1, 2, 1]
[1, 2, 0]
[0, 2, 2]
[0, 2, 1]
[0, 2, 0]
Number one, the pivotPointer does not decrement properly when the pivotPointer and currentCountdown are more than one array cell apart. Secondly, there is an arrayIndexOutOfBounds at the line counters[pivotLocation] = counters[pivotLocation] - 1; that if fixed,
breaks the algorithm from running properly alltogether.
Any help would be appreciated.
I'll suggest a different approach.
The idea in recursion is to reduce the size of the problem in each recursive call, until you reach a trivial case, in which you don't have to make another recursive call.
When you first call the recursive method for an array of n elements, you can iterate in a loop over the range of values of the last index (n-1), make a recursive call to generate all the combinations for the array of the first n-1 elements, and combine the outputs.
Here's some partial Java/ partial pseudo code :
The first call :
List<int[]> output = generateCombinations(inputArray,inputArray.length);
The recursive method List<int[]> generateCombinations(int[] array, int length) :
List<int[]> output = new ArrayList<int[]>();
if length == 0
// the end of the recursion
for (int i = array[length]; i>=0; i--)
output.add (i)
else
// the recursive step
List<int[]> partialOutput = generateCombinations(array, length - 1)
for (int i = array[length]; i>=0; i--)
for (int[] arr : partialOutput)
output.add(arr + i)
return output
The recursive method returns a List<int[]>. This means that in "output.add (i)" you should create an int array with a single element and add it to the list, while in output.add(arr + i) you'll create an array of arr.length+1 elements, and copy to it the elements of arr followed by i.
The fun thing about recursion is that you can have it do exactly what you want it to. In this case, for each number at index i of your array of counts, we want to combine it with each number at index i + 1 until we reach the end of the array. The trick is not to return to index i once you've run through all the options for it.
JavaScript code:
var arr = [3,4,5];
var n = arr.length;
function f(cs,i){
// base case
if (i == n){
console.log(cs.join(','));
return;
}
// otherwise
while (cs[i] >= 0){
// copy counts
_cs = cs.slice();
// recurse
f(_cs,i + 1);
// change number at index i
cs[i]--;
}
}
f(arr,0);
Here is the program task:
Write a method called collapse that accepts an array of integers as a parameter and returns a new array containing the result of replacing each pair of integers with the sum of that pair.
For example, if an array called list stores the values
{7, 2, 8, 9, 4, 13, 7, 1, 9, 10}
then the call of collapse(list) should return a new array containing:
{9, 17, 17, 8, 19}.
The first pair from the original list is collapsed into 9 (7 + 2), the second pair is collapsed into 17 (8 + 9), and so on. If the list stores an odd number of elements, the final element is not collapsed.
For example, if the list had been {1, 2, 3, 4, 5}, then the call would return {3, 7, 5}. Your method should not change the array that is passed as a parameter.
Here is my currently-written program:
public static int[] collapse(int[] a1) {
int newArrayLength = a1.length / 2;
int[] collapsed = new int[newArrayLength];
int firstTwoSums = 0;
for (int i = 0; i < a1.length-1; i++) {
firstTwoSums = a1[i] + a1[i+1];
collapsed[collapsed.length-1] = firstTwoSums;
}
return collapsed;
}
I pass in an array of {7, 2, 8, 9, 4, 13, 7, 1, 9, 10} and I want to replace this array with {9, 17, 17, 8, 19}.
Note:{9, 17, 17, 8, 19} will be obtained through the for-loop that I have written.
Currently, I am having trouble with adding the integers I obtained to my "collapsed" array. It'd be a great help if you could help me or at least give me some guidance on how to do this.
Thanks in advance!
First you have to understand what is going on.
You have an array of certain size where size can either be even or odd. This is important because you are using a1.length/2 to set the size for new array, so you will also have to check for odd and even values to set the size right else it won't work for odd sized arrays. Try a few cases for better understanding.
Here's a way of doing it.
public static int[] collapseThis(int[] array) {
int size = 0;
if(isEven(array.length))
size = array.length/2;
else
size = array.length/2+1;
int[] collapsedArray = new int[size];
for(int i=0, j=0; j<=size-1; i++, j++) {
if(j==size-1 && !isEven(array.length)) {
collapsedArray[j] = array[2*i];
}
else {
collapsedArray[j] = array[2*i]+array[2*i+1];
}
}
return collapsedArray;
}
private static boolean isEven(int num) {
return (num % 2 == 0);
}
Using
collapsed[collapsed.length-1] = firstTwoSums;
The sum of your numbers will be always be put in the same index of the collapsed array, because collapsed.length - 1 is a constant value.
Try creating a new variable starting at zero, that can be incremented each time you add a sum to collapsed. For instance,
int j = 0;
for(...) {
...
collapsed[j++] = firstTwoSums;
}
I think this is a convenient answer.
public static void main(String[] args){
int[] numbers = {1,2,3,4,5};
int[] newList = collapse(numbers);
System.out.println(Arrays.toString(newList));
}
public static int[] collapse(int[] data){
int[] newList = new int[(data.length + 1)/2];
int count = 0;
for (int i = 0; i < (data.length / 2); i++){
newList[i] = data[count] + data[count + 1];
System.out.println(newList[i]);
count = count + 2;
}
if (data.length % 2 == 1){
newList[(data.length / 2)] = data[data.length - 1];
}
return newList;
}
i would combine the cases for the array with either odd or even elements together as below:
public static int[] collapse(int[] a1) {
int[] res = new int[a1.length/2 + a1.length % 2];
for (int i = 0; i < a1.length; i++)
res[i/2] += a1[i];
return res;
}
public static int[] collapse(int[] a1) {
int newArrayLength = a1.length / 2;
int[] collapsed;
if(a1.length%2 == 0)
{
collapsed = new int[newArrayLength];
}
else
{
collapsed = new int[newArrayLength+1];
collapsed[newArrayLength] = a1[a1.length-1];
}
int firstTwoSums = 0;
for (int i = 0; i < newArrayLength; i++) {
firstTwoSums = a1[i*2] + a1[i*2+1];
collapsed[i] = firstTwoSums;
}
return collapsed;
}
I modified your code and you may try it first.
I have seen acrosss in a company interview test this question, but i am not clear about the question first. Could you people clarify my doubt ?
Question : Write a program to sort an integer array which contains Only 0's,1's and 2's. Counting of elements not allowed, you are expected to do it in O(n) time complexity.
Ex Array : {2, 0, 1, 2, 1, 2, 1, 0, 2, 0}
Output to a linked list.
Remember the beginning of the list.
Remember the position where the 1s start.
Remember the end of the list.
Run through the whole array.
If you encounter a 0, add it to the first position of the linked list.
If you encounter a 1, add it after the position of the 1.
If you encounter a 2, add it at the end of the list.
HTH
Raku
Instead of blasting you with yet another unintelligible pseudo-code, I’ll give you the name of the problem: this problem is known as the Dutch national flag problem (first proposed by Edsgar Dijkstra) and can be solved by a three-ways merge (see the PHP code in the first answer which solves this, albeit very inefficiently).
A more efficient in-place solution of the threeways merge is described in Bentley’s and McIlroy’s seminal paper Engineering a Sort Function. It uses four indices to delimit the ranges of the intermediate array, which has the unsorted values in the middle, the 1s at both edges, and the 0s and 2s in-between:
After having established this invariant, the = parts (i.e. the 1s) are swapped back into the middle.
It depends what you mean by "no counting allowed".
One simple way to do this would be to have a new empty array, then look for 0's, appending them to the new array. Repeat for 1's then 2's and it's sorted in O(n) time.
But this is more-or-less a radix sort. It's like we're counting the 0's then 1's then 2's, so I'm not sure if this fits your criteria.
Edit: we could do this with only O(1) extra memory by keeping a pointer for our insertion point (starting at the start of the array), and scanning through the array for 0's, swapping each 0 with the element where the pointer is, and incrementing the pointer. Then repeat for 1's, 2's and it's still O(n).
Java implementation:
import java.util.Arrays;
public class Sort
{
public static void main(String[] args)
{
int[] array = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
sort(array);
System.out.println(Arrays.toString(array));
}
public static void sort(int[] array)
{
int pointer = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < array.length; j++)
{
if(array[j] == i)
{
int temp = array[pointer];
array[pointer] = array[j];
array[j] = temp;
pointer++;
}
}
}
}
}
Gives output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
Sorry, it's php, but it seems O(n) and could be easily written in java :)
$arr = array(2, 0, 1, 2, 1, 2, 1, 0, 2, 0);
$tmp = array(array(),array(),array());
foreach($arr as $i){
$tmp[$i][] = $i;
}
print_r(array_merge($tmp[0],$tmp[1],$tmp[2]));
In O(n), pseudo-code:
def sort (src):
# Create an empty array, and set pointer to its start.
def dest as array[sizeof src]
pto = 0
# For every possible value.
for val in 0, 1, 2:
# Check every position in the source.
for pfrom ranges from 0 to sizeof(src):
# And transfer if matching (includes update of dest pointer).
if src[pfrom] is val:
dest[pto] = val
pto = pto + 1
# Return the new array (or transfer it back to the source if desired).
return dest
This is basically iterating over the source list three times, adding the elements if they match the value desired on this pass. But it's still O(n).
The equivalent Java code would be:
class Test {
public static int [] mySort (int [] src) {
int [] dest = new int[src.length];
int pto = 0;
for (int val = 0; val < 3; val++)
for (int pfrom = 0; pfrom < src.length; pfrom++)
if (src[pfrom] == val)
dest[pto++] = val;
return dest;
}
public static void main(String args[]) {
int [] arr1 = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
int [] arr2 = mySort (arr1);
for (int i = 0; i < arr2.length; i++)
System.out.println ("Array[" + i + "] = " + arr2[i]);
}
}
which outputs:
Array[0] = 0
Array[1] = 0
Array[2] = 0
Array[3] = 1
Array[4] = 1
Array[5] = 1
Array[6] = 2
Array[7] = 2
Array[8] = 2
Array[9] = 2
But seriously, if a potential employer gave me this question, I'd state straight out that I could answer the question if they wish, but that the correct answer is to just use Array.sort. Then if, and only if, there is a performance problem with that method and the specific data sets, you could investigate a faster way.
And that faster way would almost certainly involve counting, despite what the requirements were. You don't hamstring your developers with arbitrary limitations. Requirements should specify what is required, not how.
If you answered this question to me in this way, I'd hire you on the spot.
This answer doesn't count the elements.
Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up - making it match the typical java int loop.
public static void main(String[] args) throws Exception
{
Integer[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
List<Integer>[] elements = new ArrayList[3]; // To store the different element types
// Initialize the array with new lists
for (int i = 0; i < elements.length; i++) elements[i] = new ArrayList<Integer>();
// Populate the lists
for (int i : array) elements[i].add(i);
for (int i = 0, start = 0; i < elements.length; start += elements[i++].size())
System.arraycopy(elements[i].toArray(), 0, array, start, elements[i].size());
System.out.println(Arrays.toString(array));
}
Output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
Push and Pull have a constant complexity!
Push each element into a priority queue
Pull each element to indices 0...n
(:
You can do it in one pass, placing each encountered element to it's final position:
void sort012(int* array, int len) {
int* p0 = array;
int* p2 = array + len;
for (int* p = array; p <= p2; ) {
if (*p == 0) {
std::swap(*p, *p0);
p0++;
p++;
} else if (*p == 2) {
std::swap(*p, *p2);
p2--;
} else {
p++;
}
}
}
Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up - making it match the typical java int loop.
The whole sorting algorithm requires only three lines of code:
public static void main(String[] args)
{
int[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
// Line 1: Define some space to hold the totals
int[] counts = new int[3]; // To store the (3) different totals
// Line 2: Get the total of each type
for (int i : array) counts[i]++;
// Line 3: Write the appropriate number of each type consecutively back into the array:
for (int i = 0, start = 0; i < counts.length; start += counts[i++]) Arrays.fill(array, start, start + counts[i], i);
System.out.println(Arrays.toString(array));
}
Output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
At no time did we refer to array.length, no care how long the array was. It iterated through the array touching each element just once, making this algorithm O(n) as required.