In below code I'm trying to add integers at last in array if array elements matches with specific key let's say k=1 in my case. But I'm not able to figure out how to iterate array after adding elements at last in array to check if any element can be shifted to last of the array.
Also,I don't want to use any java collection.Please help me in this regard.
int[] a=new int[8];
int key=1;
int temp,c=0;
a[0]=1;a[1]=1;a[2]=2;a[3]=1;
a[4]=1;a[5]=1;a[6]=3;a[7]=4;
int l=a.length;
for(int i=0;i<l;i++) {
c=i;
if(a[i]==key) {
temp=a[i];
while(c<l-1) {
a[c]=a[c+1];
c++;
}
a[l-1]=temp;
}
}
As we can see, in above code key=1 matches with elements present at index(i=0,1,3,4,5) and I am putting elements at last and shifting all other elements to previous index but problem is that after shifting, again I need to check if array has any element which is still matching with key(k=1) and need to put at last of the array. Hope I could clear my problem.
this outputs- 12134111
but desired output is 23411111.
Meaning all elements which matches with key=1, should be put at last.
You can a little bit modify your algorithm according to this:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = new int[8];
int key = 1;
a[0] = 1;
a[1] = 1;
a[2] = 2;
a[3] = 1;
a[4] = 1;
a[5] = 1;
a[6] = 3;
a[7] = 4;
for (int i = 0; i < a.length; i++) {
if (a[i] != key) {
continue;
}
//find next element which doesn't equal to key and swap
for (int j = i; j < a.length; j++) {
if (a[j] != a[i]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
break;
}
}
}
System.out.println(Arrays.toString(a));
}
}
Output: [2, 3, 4, 1, 1, 1, 1, 1]
public static void main(String args[])
{
int a[]={1,1,2,1,1,1,3,3};
int k=1,n=a.length-1;
for(int i=0;i<a.length;i++)
{
if(a[i]==k)
{
int temp=a[i];
for (int j=i;j<n-1;j++)
{
a[j]=a[j+1];
}
a[n]=temp;
}
}
}
I'm trying to make a selection sort algorithm in java that finds the smallest element of an unsorted array and puts it on the end of a new array. But my program only copies the first element twice, gets the next one, and then the rest is all zeroes:
public static int find_min(int[] a){
int m = a[0];
for (int i = 0; i < a.length; i++){
if (m > a[i])
m = a[i];
}
return m;
}
public static int[] selectionSort(int[] unsorted){
int[] c = new int[unsorted.length];
for(int i = 0; i < unsorted.length; i++){
int smallest = find_min(unsorted);
c[i] = smallest;
unsorted = Arrays.copyOfRange(unsorted, i+1, unsorted.length );
}
return c;
}
When I put in something like:
public static void main(String[] args){
int a[] = {1,-24,4,-4,6,3};
System.out.println(Arrays.toString(selectionSort(a)));
}
I get:
[-24, -24, -4, 0, 0, 0]
where is this going wrong? Is this a bad algorithm?
Ok, let's revisit the selection sort algorithm.
public static void selectionSort(int[] a) {
final int n = a.length; // to save some typing.
for (int i = 0; i < n - 1; i++) {
// i is the position where the next smallest element should go.
// Everything before i is sorted, and smaller than any element in a[i:n).
// Now you find the smallest element in subarray a[i:n).
// Actually, you need the index
// of that element, because you will swap it with a[i] later.
// Otherwise we lose a[i], which is bad.
int m = i;
for (int j = m + 1; j < n; j++) {
if (a[j] < a[m]) m = j;
}
if (m != i) {
// Only swap if a[i] is not already the smallest.
int t = a[i];
a[i] = a[m];
a[m] = t;
}
}
}
In conclusion
You don't need extra space to do selection sort
Swap elements, otherwise you lose them
Remembering the loop invariant is helpful
Can anyone say what is the problem in the merging logic? If element of right array is less than element in left array then it works. Other wise gives wrong answer. I have divided the array properly. I am giving my merging logic here.
public static void main(String[] args) {
int[] list = { 32,14, 67, 76, 23, 41, 58, 85};
System.out.println("before: " + Arrays.toString(list));
mergeSort(list);
System.out.println("after: " + Arrays.toString(list));
}
public static void mergeSort(int[] array) {
if (array.length > 1) {
// split array into two halves
int[] left = leftHalf(array);
int[] right = rightHalf(array);
mergeSort(left);
mergeSort(right);
merge(array, left, right);
}
}
public static void merge(int[] result,
int[] left, int[] right) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
int j = 0;
int k = 0;
for (int i=0; i1 < left.length && i2 < right.length;i++) {
if (left[i1] < right[i2]) {
result[i] = left[i1];
// take from left
i1++;
} else {
result[i] = right[i2];
// take from right
i2++;
}
}
}
You've got two unused variables j and k in your code. Your logic is flawed because you copy into the array until one half is empty, so you never actually empty both halves.
public static void merge(int[] result, int[] left, int[] right) {
int i1 = 0; // index into left array
int i2 = 0; // index into right array
int i;
for (i = 0; i1 < left.length && i2 < right.length;i++) {
if (left[i1] < right[i2]) {
result[i] = left[i1++];
// take from left
} else {
result[i] = right[i2++];
// take from right
}
}
for (; i1 < left.length; i++) result[i] = left[i1++];
for (; i2 < right.length; i++) result[i] = right[i2++];
}
Only one of the two for loops will run at the end, and will process what's left of the other half.
public class intersect {
public static void find(int[] a, int[] b, int[] acc)
{
int position = 0;
for (int j = 0; j < a.length; j++) {
for (int k = 0; k<b.length; k++) {
if (a[j] == b[k]) {
acc[position] = b[k];
position++;
}
}
}
System.out.println(java.util.Arrays.toString(acc));
}
public static void main (String[] s)
{
int[] acc = new int[2];
int[] a = {1,2,3};
int[] b = {2,3,4};
find(a, b, acc);
}
}
I have written the above code to solve the problem.
But if you see, the function is very limited because I have to change the length of the acc every time. That means I have to know how many elements are intersecting. In this case, the array {1,2,3} and {2,3,4} have {2,3} in common, so the length of the acc would be 2.
I am sure there are millions of ways of tackling this problem, but I cannot seem to think of a way of fixing this.
Please help!
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find() method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
To find intersection of 2 sorted arrays, follow the below approach :
1) Use two index variables i and j, initial values with 0
2) If array1 is smaller than array2 then increment i.
3) If array1 is greater than array2 then increment j.
4) If both are same then print any of them and increment both i and j.
check this link for more information
https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
public class FindIntersection {
static void findInterSection(int array1[], int array2[], int array1NoOfElements, int
array2NoOfElements) {
int i = 0, j = 0;
while (i < array1NoOfElements && j < array2NoOfElements) {
if (array1[i] < array2[j]) {
i++;
} else if (array2[j] < array1[i]) {
j++;
}
// if both array elements are same
else {
System.out.println(array2[j++] + " ");
i++;
}
}
}
public static void main(String[] args)
{
int myFirstArray[] = { 1, 2, 4, 5, 5 };
int mySecondArray[] = { 2, 3, 5, 7 };
int m = myFirstArray.length;
int n = mySecondArray.length;
findInterSection(myFirstArray, mySecondArray, m, n);
}
}
Make your intersection array's size the size of the smaller of your original arrays. That way, you won't ever have to increase it's capacity.
Then you can use Arrays.copy to transfer your results into an appropriately sized array.
Not sure if this is the best solution, but you don't need to hard-code the size of the intersection ahead of time (which is one thing you were concerned about).
As you iterate through both arrays, you can add elements found in both sets to a StringBuilder (along with some delimiter, I used a comma in the example below). Once you're finished, you can call toString() & then split() using the delimiter afterwards to get a String[]. At that point, you can put convert those String objects to int primitives & return an int[].
public class Scratch {
public static void main(String[] s) {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] intersection = findIntersection(a, b);
System.out.println(Arrays.toString(intersection));
}
public static int[] findIntersection(int[] a, int[] b) {
StringBuilder intersectionStringBuilder = new StringBuilder();
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (a[j] == b[k])
intersectionStringBuilder.append(a[j] + ",");
}
}
String[] intersectionStringArray = intersectionStringBuilder.toString().split(",");
int[] intersection = new int[intersectionStringArray.length];
for (int current = 0; current < intersectionStringArray.length; current++) {
intersection[current] = Integer.parseInt(intersectionStringArray[current]);
}
return intersection;
}
}
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j] && !index.contains(j)){
list.add(arr1[i]);
index.add(j);
break;
}
}
}
int result[]=new int[list.size()];
int k=0;
for(int i:list){
result[k]=i;
k++;
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
return result;
}
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));
}}