So the goal is to rotate the elements in an array right a times.
As an example; if a==2, then array = {0,1,2,3,4} would become array = {3,4,0,1,2}
Here's what I have:
for (int x = 0; x <= array.length-1; x++){
array[x+a] = array[x];
}
However, this fails to account for when [x+a] is greater than the length of the array. I read that I should store the ones that are greater in a different Array but seeing as a is variable I'm not sure that's the best solution.
Thanks in advance.
Add a modulo array length to your code:
// create a newArray before of the same size as array
// copy
for(int x = 0; x <= array.length-1; x++){
newArray[(x+a) % array.length ] = array[x];
}
You should also create a new Array to copy to, so you do not overwrite values, that you'll need later on.
In case you don't want to reinvent the wheel (maybe it's an exercise but it can be good to know), you can use Collections.rotate.
Be aware that it requires an array of objects, not primitive data type (otherwise you'll swap arrays themselves in the list).
Integer[] arr = {0,1,2,3,4};
Collections.rotate(Arrays.asList(arr), 2);
System.out.println(Arrays.toString(arr)); //[3, 4, 0, 1, 2]
Arraycopy is an expensive operation, both time and memory wise.
Following would be an efficient way to rotate array without using extra space (unlike the accepted answer where a new array is created of the same size).
public void rotate(int[] nums, int k) { // k = 2
k %= nums.length;
// {0,1,2,3,4}
reverse(nums, 0, nums.length - 1); // Reverse the whole Array
// {4,3,2,1,0}
reverse(nums, 0, k - 1); // Reverse first part (4,3 -> 3,4)
// {3,4,2,1,0}
reverse(nums, k, nums.length - 1); //Reverse second part (2,1,0 -> 0,1,2)
// {3,4,0,1,2}
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
Another way is copying with System.arraycopy.
int[] temp = new int[array.length];
System.arraycopy(array, 0, temp, a, array.length - a);
System.arraycopy(array, array.length-a, temp, 0, a);
I think the fastest way would be using System.arrayCopy() which is native method:
int[] tmp = new int[a];
System.arraycopy(array, array.length - a, tmp, 0, a);
System.arraycopy(array, 0, array, a, array.length - a);
System.arraycopy(tmp, 0, array, 0, a);
It also reuses existing array. It may be beneficial in some cases.
And the last benefit is the temporary array size is less than original array. So you can reduce memory usage when a is small.
Time Complexity = O(n)
Space Complexity = O(1)
The algorithm starts with the first element of the array (newValue) and places it at its position after the rotation (newIndex). The element that was at the newIndex becomes oldValue. After that, oldValue and newValue are swapped.
This procedure repeats length times.
The algorithm basically bounces around the array placing each element at its new position.
unsigned int computeIndex(unsigned int len, unsigned int oldIndex, unsigned int times) {
unsigned int rot = times % len;
unsigned int forward = len - rot;
// return (oldIndex + rot) % len; // rotating to the right
return (oldIndex + forward) % len; // rotating to the left
}
void fastArrayRotation(unsigned short *arr, unsigned int len, unsigned int rotation) {
unsigned int times = rotation % len, oldIndex, newIndex, length = len;
unsigned int setIndex = 0;
unsigned short newValue, oldValue, tmp;
if (times == 0) {
return;
}
while (length > 0) {
oldIndex = setIndex;
newValue = arr[oldIndex];
while (1) {
newIndex = computeIndex(len, oldIndex, times);
oldValue = arr[newIndex];
arr[newIndex] = newValue;
length--;
if (newIndex == setIndex) { // if the set has ended (loop detected)
break;
}
tmp = newValue;
newValue = oldValue;
oldValue = tmp;
oldIndex = newIndex;
}
setIndex++;
}
}
int[] rotate(int[] array, int r) {
final int[] out = new int[array.length];
for (int i = 0; i < array.length; i++) {
out[i] = (i < r - 1) ? array[(i + r) % array.length] : array[(i + r) % array.length];
}
return out;
}
The following rotate method will behave exactly the same as the rotate method from the Collections class used in combination with the subList method from the List interface, i.e. rotate (n, fromIndex, toIndex, dist) where n is an array of ints will give the same result as Collections.rotate (Arrays.asList (n).subList (fromIndex, toIndex), dist) where n is an array of Integers.
First create a swap method:
public static void swap (int[] n, int i, int j){
int tmp = n[i];
n[i] = n[j];
n[j] = tmp;
}
Then create the rotate method:
public static void rotate (int[] n, int fromIndex, int toIndex,
int dist){
if(fromIndex > toIndex)
throw new IllegalArgumentException ("fromIndex (" +
fromIndex + ") > toIndex (" + toIndex + ")");
if (fromIndex < toIndex){
int region = toIndex - fromIndex;
int index;
for (int i = 0; i < dist % region + ((dist < 0) ? region : 0);
i++){
index = toIndex - 1;
while (index > fromIndex)
swap (n, index, --index);
}
}
}
Java solution wrapped in a method:
public static int[] rotate(final int[] array, final int rIndex) {
if (array == null || array.length <= 1) {
return new int[0];
}
final int[] result = new int[array.length];
final int arrayLength = array.length;
for (int i = 0; i < arrayLength; i++) {
int nIndex = (i + rIndex) % arrayLength;
result[nIndex] = array[i];
}
return result;
}
For Left Rotate its very simple
Take the difference between length of the array and number of position to shift.
For Example
int k = 2;
int n = 5;
int diff = n - k;
int[] array = {1, 2, 3, 4, 5};
int[] result = new int[array.length];
System.arraycopy(array, 0, result, diff, k);
System.arraycopy(array, k, result, 0, diff);
// print the output
Question : https://www.hackerrank.com/challenges/ctci-array-left-rotation
Solution :
This is how I tried arrayLeftRotation method with complexity o(n)
looping once from k index to (length-1 )
2nd time for 0 to kth index
public static int[] arrayLeftRotation(int[] a, int n, int k) {
int[] resultArray = new int[n];
int arrayIndex = 0;
//first n-k indexes will be populated in this loop
for(int i = k ; i
resultArray[arrayIndex] = a[i];
arrayIndex++;
}
// 2nd k indexes will be populated in this loop
for(int j=arrayIndex ; j<(arrayIndex+k); j++){
resultArray[j]=a[j-(n-k)];
}
return resultArray;
}
package com.array.orderstatistics;
import java.util.Scanner;
public class ArrayRotation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int r = scan.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
}
scan.close();
if (r % n == 0) {
printOriginalArray(a);
} else {
r = r % n;
for (int i = 0; i < n; i++) {
b[i] = a[(i + r) < n ? (i + r) : ((i + r) - n)];
System.out.print(b[i] + " ");
}
}
}
private static void printOriginalArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
Following routine rotates an array in java:
public static int[] rotateArray(int[] array, int k){
int to_move = k % array.length;
if(to_move == 0)
return array;
for(int i=0; i< to_move; i++){
int temp = array[array.length-1];
int j=array.length-1;
while(j > 0){
array[j] = array[--j];
}
array[0] = temp;
}
return array;
}
You can do something like below
class Solution {
public void rotate(int[] nums, int k) {
if (k==0) return;
if (nums == null || nums.length == 0) return;
for(int i=0;i<k;i++){
int j=nums.length-1;
int temp = nums[j];
for(;j>0;j--){
nums[j] = nums[j-1];
}
nums[0] = temp;
}
}
}
In the above solution, k is the number of times you want your array to rotate from left to right.
Question : Rotate array given a specific distance .
Method 1 :
Turn the int array to ArrayList. Then use Collections.rotate(list,distance).
class test1 {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Collections.rotate(list, 3);
System.out.println(list);//[4, 5, 6, 1, 2, 3]
}// main
}
I use this, just loop it a times
public void rotate(int[] arr) {
int temp = arr[arr.length - 1];
for(int i = arr.length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
Related
I have an array of objects in Java, and I am trying to pull one element to the top and shift the rest down by one.
Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0 and all elements from 0 to 5 will be shifted down by one.
This algorithm does not properly shift the elements:
Object temp = pool[position];
for (int i = 0; i < position; i++) {
array[i+1] = array[i];
}
array[0] = temp;
How do I do it correctly?
Logically it does not work and you should reverse your loop:
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
Alternatively you can use
System.arraycopy(array, 0, array, 1, position);
Assuming your array is {10,20,30,40,50,60,70,80,90,100}
What your loop does is:
Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}
Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}
What you should be doing is
Object temp = pool[position];
for (int i = (position - 1); i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
You can just use Collections.rotate(List<?> list, int distance)
Use Arrays.asList(array) to convert to List
more info at: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)
Instead of shifting by one position you can make this function more general using module like this.
int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;
for(int i=0; i<original.length;i++)
reordered[i] = original[(shift+i)%original.length];
Just for completeness: Stream solution since Java 8.
final String[] shiftedArray = Arrays.stream(array)
.skip(1)
.toArray(String[]::new);
I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.
Manipulating arrays in this way is error prone, as you've discovered. A better option may be to use a LinkedList in your situation. With a linked list, and all Java collections, array management is handled internally so you don't have to worry about moving elements around. With a LinkedList you just call remove and then addLast and the you're done.
Try this:
Object temp = pool[position];
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
array[0] = temp;
Look here to see it working: http://www.ideone.com/5JfAg
Using array Copy
Generic solution for k times shift k=1 or k=3 etc
public void rotate(int[] nums, int k) {
// Step 1
// k > array length then we dont need to shift k times because when we shift
// array length times then the array will go back to intial position.
// so we can just do only k%array length times.
// change k = k% array.length;
if (k > nums.length) {
k = k % nums.length;
}
// Step 2;
// initialize temporary array with same length of input array.
// copy items from input array starting from array length -k as source till
// array end and place in new array starting from index 0;
int[] tempArray = new int[nums.length];
System.arraycopy(nums, nums.length - k, tempArray, 0, k);
// step3:
// loop and copy all the remaining elements till array length -k index and copy
// in result array starting from position k
for (int i = 0; i < nums.length - k; i++) {
tempArray[k + i] = nums[i];
}
// step 4 copy temp array to input array since our goal is to change input
// array.
System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
}
code
public void rotate(int[] nums, int k) {
if (k > nums.length) {
k = k % nums.length;
}
int[] tempArray = new int[nums.length];
System.arraycopy(nums, nums.length - k, tempArray, 0, k);
for (int i = 0; i < nums.length - k; i++) {
tempArray[k + i] = nums[i];
}
System.arraycopy(tempArray, 0, nums, 0, tempArray.length);
}
In the first iteration of your loop, you overwrite the value in array[1]. You should go through the indicies in the reverse order.
static void pushZerosToEnd(int arr[])
{ int n = arr.length;
int count = 0; // Count of non-zero elements
// Traverse the array. If element encountered is non-zero, then
// replace the element at index 'count' with this element
for (int i = 0; i < n; i++){
if (arr[i] != 0)`enter code here`
// arr[count++] = arr[i]; // here count is incremented
swapNumbers(arr,count++,i);
}
for (int j = 0; j < n; j++){
System.out.print(arr[j]+",");
}
}
public static void swapNumbers(int [] arr, int pos1, int pos2){
int temp = arr[pos2];
arr[pos2] = arr[pos1];
arr[pos1] = temp;
}
Another variation if you have the array data as a Java-List
listOfStuff.add(
0,
listOfStuff.remove(listOfStuff.size() - 1) );
Just sharing another option I ran across for this, but I think the answer from #Murat Mustafin is the way to go with a list
public class Test1 {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5, 6 };
Test1 test = new Test1();
x = test.shiftArray(x, 2);
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public int[] pushFirstElementToLast(int[] x, int position) {
int temp = x[0];
for (int i = 0; i < x.length - 1; i++) {
x[i] = x[i + 1];
}
x[x.length - 1] = temp;
return x;
}
public int[] shiftArray(int[] x, int position) {
for (int i = position - 1; i >= 0; i--) {
x = pushFirstElementToLast(x, position);
}
return x;
}
}
A left rotation operation on an array of size n shifts each of the array's elements unit to the left, check this out!!!!!!
public class Solution {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]); //no. of elements in the array
int d = Integer.parseInt(nd[1]); //number of left rotations
int[] a = new int[n];
for(int i=0;i<n;i++){
a[i]=scanner.nextInt();
}
Solution s= new Solution();
//number of left rotations
for(int j=0;j<d;j++){
s.rotate(a,n);
}
//print the shifted array
for(int i:a){System.out.print(i+" ");}
}
//shift each elements to the left by one
public static void rotate(int a[],int n){
int temp=a[0];
for(int i=0;i<n;i++){
if(i<n-1){a[i]=a[i+1];}
else{a[i]=temp;}
}}
}
You can use the Below codes for shifting not rotating:
int []arr = {1,2,3,4,5,6,7,8,9,10,11,12};
int n = arr.length;
int d = 3;
Programm for shifting array of size n by d elements towards left:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {4,5,6,7,8,9,10,11,12,10,11,12}
public void shiftLeft(int []arr,int d,int n) {
for(int i=0;i<n-d;i++) {
arr[i] = arr[i+d];
}
}
Programm for shifting array of size n by d elements towards right:
Input : {1,2,3,4,5,6,7,8,9,10,11,12}
Output: {1,2,3,1,2,3,4,5,6,7,8,9}
public void shiftRight(int []arr,int d,int n) {
for(int i=n-1;i>=d;i--) {
arr[i] = arr[i-d];
}
}
import java.util.Scanner;
public class Shift {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int array[] = new int [5];
int array1[] = new int [5];
int i, temp;
for (i=0; i<5; i++) {
System.out.printf("Enter array[%d]: \n", i);
array[i] = input.nextInt(); //Taking input in the array
}
System.out.println("\nEntered datas are: \n");
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
}
temp = array[4]; //We declared the variable "temp" and put the last number of the array there...
System.out.println("\nAfter Shifting: \n");
for(i=3; i>=0; i--) {
array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
}
for (i=0; i<5; i++) {
System.out.printf("array[%d] = %d\n", i, array1[i]);
}
input.close();
}
}
Write a Java program to create an array of 20 integers, and then implement the process of shifting the array to right for two elements.
public class NewClass3 {
public static void main (String args[]){
int a [] = {1,2,};
int temp ;
for(int i = 0; i<a.length -1; i++){
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
for(int p : a)
System.out.print(p);
}
}
I want to find the K smallest elements in an array, and I was able to basically sort my array into a min-heap structure but I am still getting the wrong output.
Here are my inputs:
arr = [9,4,7,1,-2,6,5]
k = 3
Here's the Code:
public static int[] findKSmallest(int[] arr, int k) {
int[] result = new int[k];
int heapSize = arr.length;
// Write - Your - Code
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
minHeap(arr, i, heapSize);
}
for (int j = 0; j < k; j++) {
result[j] = arr[j];
}
return result;
}
public static void minHeap(int[] arr, int index, int heapSize) {
int smallest = index;
while (smallest < heapSize / 2) {
int left = (2 * index) + 1; // 1 more than half the index
int right = (2 * index) + 2; // 2 more than half the index
if (left < heapSize && arr[left] < arr[index]) {
smallest = left;
}
if (right < heapSize && arr[right] < arr[smallest]) {
smallest = right;
}
if (smallest != index) {
int temp = arr[index];
arr[index] = arr[smallest];
arr[smallest] = temp;
index = smallest;
} else {
break;
}
}
}
Here is my expected output:
[-2,1,4]
Though my output is:
[-2,1,5]
Please I would like to know where I went wrong.
After you build your minHeap you have to extract element and appropriately adjust tree. You simply took elements from array by index, which is not how heap works.
I slightly modified your minHeap() method to use recursion and you should check arr[smallest] < arr[left] not the orther way around.
public static int[] findKSmallest(int[] arr, int k) {
int[] result = new int[k];
int heapSize = arr.length;
// Write - Your - Code
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
minHeap(arr, heapSize, i);
}
// extract elements from heap
for (int i = heapSize - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
minHeap(arr, 0, i);
}
for (int j = 0; j < k; j++) {
result[j] = arr[j];
}
return result;
}
public static void minHeap(int[] arr, int index, int heapSize) {
int smallest = index;
int left = (2 * index) + 1; // 1 more than half the index
int right = (2 * index) + 2; // 2 more than half the index
if (left < heapSize && arr[smallest] < arr[left]) {
smallest = left;
}
if (right < heapSize && arr[smallest] < arr[right]) {
smallest = right;
}
if (smallest != index) {
int temp = arr[index];
arr[index] = arr[smallest];
arr[smallest] = temp;
minHeap(arr, smallest, heapSize);
}
}
Hope this helps. As expected the result is:
[-2, 1, 4]
You can use Arrays.stream​(int[]) method:
int[] arr = {9, 4, 7, 1, -2, 6, 5};
int k = 3;
int[] minHeap = Arrays.stream(arr).sorted().limit(k).toArray();
System.out.println(Arrays.toString(minHeap)); // [-2, 1, 4]
Since Java 8 we can do Sorting stream
Alternative code:
Arrays.stream(arr).sorted().boxed().collect(Collectors.toList()).subList(0, k);
where:
int[] arr = {9,4,7,1,-2,6,5};
int k = 3; // toIndex
Alternative code in context and testbench:
public static void main(String[] args) {
int[] arr = {9, 4, 7, 1, -2, 6, 5};
int k = 3; // toIndex
List<Integer> listResult = Arrays.stream(arr)
.sorted().boxed().collect(Collectors.toList()).subList(0, k);
// print out list result
System.out.println("Output of list result: " + listResult);
int[] arrayResult = listResult.stream().mapToInt(i -> i).toArray();
// print out array result
List<String> arrayResultAsString = Arrays.stream(arrayResult)
.boxed().map(i -> String.valueOf(i)).collect(Collectors.toList());
System.out.println("Output of array result: " + arrayResultAsString);
}
Output:
Output of list result: [-2, 1, 4]
Output of array result: [-2, 1, 4]
If K is relatively small to the array size my recommendation is to use selection sort, so it may be a design pattern Strategy - depending on K to array size relation with for example two procedures: selection sort for small K and quicksort for huge K. Instead of playing with design patterns good may be also simple if statement e.g. selection<=30%<quick
I was trying to sort two arrays with non sequential numbers into one array after I did with sequential numbers. Do I need to order the arrays separately or is there a more effective way?
If I run the code below my output will be 4,16,2,11,19.. and it should be 0,1,2,3,4..
int myFirstArray [] = { 16, 2, 11, 34, 77, 1, 0, 10, 3 };
int mySecondArray [] = { 4, 19, 6, 32, 8, 10, 66 };
int firstPos = 0, secondPos = 0;
int myThirdArray [] = new int[myFirstArray.length + mySecondArray.length];
for (int i = 0; i < myThirdArray.length; i++) {
if (firstPos < myFirstArray.length && secondPos < mySecondArray.length) {
if (mySecondArray[secondPos] < myFirstArray[firstPos]) {
myThirdArray[i] = mySecondArray[secondPos];
secondPos++;
}
else {
myThirdArray[i] = myFirstArray[firstPos];
firstPos++;
}
}
else if (secondPos < mySecondArray.length) {
myThirdArray[i] = mySecondArray[secondPos];
secondPos++;
}
else {
myThirdArray[i] = myFirstArray[firstPos];
firstPos++;
}
}
for(int i = 0; i < myThirdArray.length; i++) {
System.out.println(myThirdArray[i]);
}
If you had 2 sorted arrays and want to combine them into one sorted array then your code would be correct. But you are comparing the first 2 elements of your unsorted arrays and create a topically sorted array, meaning some elements of the array are sorted compared to others ie 4 < 16, 2 < 11 < 19.
Your logic is not far away from Mergesort. You split your array into halves and split them again and merges the 2 halves. You end up merging arrays of size 1, then merging arrays of size 2 and so on and so on. Your merging code is correct. You can see more details here.
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
It is always better to sort your both arrays first and then merge both the array in single array.
// Function to merge array in sorted order
// a[] will be the first unsorted array.
// b[] will be the second unsorted array.
public static int[] sortedMerge(int a[], int b[]){
int n = a.length;
int m = b.length;
int totalSize=n+m;
//result array
int[] res =new int[totalSize];
// Sorting a[] and b[]
Arrays.sort(a);
Arrays.sort(b);
// Merge two sorted arrays into res[]
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] <= b[j]) {
res[k] = a[i];
i += 1;
k += 1;
} else {
res[k] = b[j];
j += 1;
k += 1;
}
}
while (i < n) { // Merging remaining
// elements of a[] (if any)
res[k] = a[i];
i += 1;
k += 1;
}
while (j < m) { // Merging remaining
// elements of b[] (if any)
res[k] = b[j];
j += 1;
k += 1;
}
return res;
}
This way the Time Complexity will be O(nlogn + mlogm + (n + m)) and
Space Complexity will be O ( (n + m) ). If you think to merge the array first and then sort the merged array then the space complexity will be the same but time complexity will change to O((n + m)(log(n + m))), which will be definitely higher than first one .
create a new array3 with size sum of array1.length and array2.length
use System.arrayCopy() to copy array1 to array3 starting at index 0
use System.arrayCopy() to copy array2 to array3 starting at index array1.length
sort array3 in the way you prefer e.g. Arrays.sort() or any other algorithm
How do I add say 1000, 10000, 1000000, or 10000000 individual data items to a search algorithm?
Code:
public class BinarySearch {
int binarySearch(int[] array, int value, int left, int right) {
if (left > right)
return -1;
int middle = (left + right) / 2;
if (array[middle] == value)
return middle;
else if (array[middle] > value)
return binarySearch(array, value, left, middle - 1);
else
return binarySearch(array, value, middle + 1, right);
}
}
So, if I understand correctly, you want to try your algorithm with different amounts of integers in your array.
public int[] makeArray(int size, int minNum, int maxNum) {
int [] arr = new int[size];
Random r = new Random();
for (int i = 0; i < size; i++) {
arr[i] = minNum + r.nextInt(maxNum);
}
Arrays.sort(arr);
return arr;
}
So if you want to have 10000 numbers ranging from 100 to 500, then you would call:
int[] arr = makeArray(10000, 100, 500);
Actually, I recommend making a helper method to start off your searches like so:
public int binarySearch(int[] array, int value) {
return binarySearch(array, value, 0, array.length - 1);
}
Then you can look in arr for a value (e.g., 5):
int i = binarySearch(arr, 5);
It seems that you are asking how to populate the array. Here is one way to do it:
final Random rnd = new Random();
final int n = 100000;
final int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = rnd.nextInt();
}
Arrays.sort(array);
How to sort array
int[] A = {0,1,1,0,1,0,1,1,0}
You can actually sort this array by traversing the array only once.
Here is the snippet of my code:
int arr[] = {1,1,1,1,0, 0,1,0,1,1,1};
int arrb[] = new int[arr.length];
int zeroInsertIndex = 0;
int oneInsertIndex =arrb.length-1;
for(int i=0; i<arr.length; i++){
if(arr[i] == 1)
arrb[oneInsertIndex--] = 1;
else if (arr[i] == 0)
arrb[zeroInsertIndex++] = 0;
}
for(int i=0;i<arrb.length;i++)
System.out.print(arrb[i] + " ");
Although Arrays.sort is an obvious, simple, O(n log n) solution, there is an O(n) solution for this special case:
Count the number of zeros, zeroCount.
Fill the first zeroCount elements with 0, the remaining elements with 1.
This takes just two passes over the array.
More generally, any array with only a small number of distinct values can be sorted by counting how many times each value appears, then filling in the array accordingly.
use any sorting algorithm to do it. For beginner use bubble sort (easy to understand)
Refer Wiki
public static void bubble_srt( int a[], int n ){
int i, j,t=0;
for(i = 0; i < n; i++){
for(j = 1; j < (n-i); j++){
if(a[j-1] > a[j]){
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}
}
}
}
EDITED
As #Pradeep Said: You may definitely use Array.sort()
Your array contains only zeros and one so sum all the elements in the array and then reset the array with those many '1's in the end and rest '0's in the beginning. Time complexity is also O(n) with constant space. So it seems the best and easy one.
public static void main(String[] args) {
int[] A = { 0, 1, 1, 0, 1, 0, 1, 1, 0 };
int sum = 0;
for (int i = 0; i < A.length; i++)
sum = sum + A[i];
Arrays.fill(A, A.length - sum, A.length, 1);
Arrays.fill(A, 0, A.length - sum, 0);
System.out.println(Arrays.toString(A));
}
Try this I implemented the above algorithm.
Output:
[0, 0, 0, 0, 1, 1, 1, 1, 1]
You can use Arrays.sort method from Arrays class:
int[] A = {0,1,1,0,1,0,1,1,0};
Arrays.sort(A);
System.out.println(A);
Actually standard off-the-shelf sorting algorithms will typically work on O(n*log(n)). You could just run through the array once adding all the values (i.e. the number of 1). Let's say you put this in count1. Then go once more over the array setting the first count1 positions to 1, and the rest to 0. It takes 2n steps.
Of course, as other posters said: this kind of optimizations is what you do once you've detected a bottleneck, not right off the bat when you start.
Arrays.sort(A,Collections.reverseOrder());
USE
Arrays.sort(A);
method to sort your array.
You can try like this also
public static void main(String[] args) {
int inputArray[] = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0 };
formatInputArray(inputArray);
}
private static void formatInputArray(int[] inputArray) {
int count = 0;
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == 0) {
count++;
}
}
// System.out.println(count);
for (int i = 0; i < inputArray.length; i++) {
if (i < count) {
inputArray[i] = 0;
}
else {
inputArray[i] = 1;
}
}
for (int i = 0; i < inputArray.length; i++) {
System.out.print(inputArray[i] + " , ");
}
}
Sort Array which contains only 0,1 and 2
import java.util.*;
public class HelloWorld {
static void sort012(int []a, int length) {
int start = 0;
int mid = 0;
int end = length - 1;
int temp;
while(mid<=end) {
switch(a[mid]) {
case 0:
temp = a[start];
a[start] = a[mid];
a[mid] = temp;
start++;
mid++;
break;
case 1:
mid++;
break;
case 2:
temp = a[end];
a[end] = a[mid];
a[mid] = temp;
end--;
break;
}
}
}
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for (int i =0;i<n; i++)
a[i] = sc.nextInt();
HelloWorld.sort012(a, n);
// Print the sorted Array
for (int i =0;i<n; i++)
System.out.println(a[i]);
}
}
var binaryArr = [1,1,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0];
//i - starting index
//j - ending index
function binarySort(arr){
var i=0,j=arr.length-1;
for(;i!=j;){
if(arr[i] == 1){
if(arr[j] == 0){
arr[i] = 0;
arr[j] = 1;
j--;
i++;
} else {
j--;
}
}else{
i++;
}
}
}
binarySort(binaryArr);
Team
Please consider the below program in Swift in o(n) time complexity and constant extra space.
import UIKit
var inputArray = [1,0,1,0,0,0,0,1,1,1,1,1,1]
var leftIndex: Int = 0
var rightIndex: Int = inputArray.count-1
while leftIndex < rightIndex{
while inputArray[leftIndex] == 0 && leftIndex < rightIndex{
leftIndex = leftIndex+1
}
while inputArray[rightIndex] == 1 && rightIndex > leftIndex {
rightIndex = rightIndex-1
}
if leftIndex < rightIndex{
inputArray[leftIndex] = 0
inputArray[rightIndex] = 1
leftIndex = leftIndex+1
rightIndex = rightIndex-1
}
}
print(inputArray)
Sort 0 and 1 array using below code:
public static int[] sortArray(int[] array){
int first = 0;
int last = array.length-1;
while(first<last){
if(array[first]==0){
first++;
}else if(array[last] == 0){
int temp = array[last];
array[last] = array[first];
array[first] = temp;
first++;
}else{
last--;
}
}
return array;
}
public static void sort(int a[]) {
int sum=0;
int b[]= new int [a.length];
for(int i=0;i<a.length;i++) {
sum=sum+a[i];
}
System.out.println(sum);
int j=b.length-1;
while(sum>0) {
b[j]=1;
sum--;
j--;
}
System.out.println(Arrays.toString(b));
}
public class Test {
public static void main(String[] args) {
int[] arr = {0, 1, 0, 1, 0, 0, 1, 1, 1, 0};
int start = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
arr[start] = 0;
if (i != start) { // should not override same value with 1
arr[i] = 1;
}
start++;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
//complexity is O(n)
If its just 0's and 1's, it can be done using two pointers.
c# code snippet :
int i = 0; int j = input.Length - 1;
while (i < j)
{
if (input[i] == 0 && input[j] == 0)
i++;
else if(input[i] == 1 && input[j] == 1)
j--;
else if (input[i] > input[j])
{
input[i++] = 0;
input[j--] = 1;
}
else
{
i++; j--;
}
}
int[] a = {0,1,1,0,1,0,1,1,0}
Here, we are iterating with i where i starts from 1. so we can compare previous index value with the current value of i. Used swapping technique to sort the array.
Note: Sort/2 pointer technique we can also use.
public int[] sort(int[] a){
int temp=0;
for(int i=1;i<a.length;i++){
if( a[i-1] > a[i]){
temp = a[i-1];
a[i-1] = a[i];
a[i] = temp;
}
}
return a[i];
}
Time complexity : O(n)
The following code will sort your array. Please notice that it does so in place - so it modifies the object in memory instead of returning a new one.
In Python
arr=[0,1,0,0,1,1,1,0,1,1,0]
arr.sort()
print(arr)
In Java
public class test{
public static void main(String[] args){
int[] arr= {0,1,0,0,1,1,1,0,1,1,0};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}}