Swapping adjacent numbers in arrays - java

Here's the problem: Write a method called swapPairs that accepts an array of integers and swaps the elements at adjacent indexes. That is, elements 0 and 1 are swapped, elements 2 and 3 are swapped, and so on. If the array has an odd length, the final element should be left unmodified. For example, the list {10,20,30,40,50} should become {20,10,40,30,50} after a call to your method.
Write method printArray that is passed an array and will print out each element.
Use this method to print the array modified by swapPairs.
This is my code:
public static void swapPairs(int[] a){
int len=a.length;
if(len%2 ==0){
for(int i=0; i<len; i=i+2){
a[i]=a[i+1];
a[i+1]=a[i];
int[] b={a[i]+a[i+1]};
}
}
if(len%2 !=0){
for(int j=0; j<len; j=j+2){
a[j]=a[j+1];
a[j+1]=a[j];
a[len-1]=a[len-1];
int[] b={a[j]+a[j+1]+a[len-1]};
}
}
}
public static void printArray(int[] a){
System.out.println(a);
}
However, what it returns is [I#2a139a55

What you need to print is Arrays.toString(a)
Now, you are just printing the Hashcode of your Array object

First, your swap method could be simplified. Add both numbers together, and then subtract each from the sum (to get the other number). Something like,
public static void swapPairs(int[] a) {
for (int i = 0; i < a.length - 1; i += 2) {
int c = a[i] + a[i + 1];
a[i] = c - a[i];
a[i + 1] = c - a[i + 1];
}
}
Then you could use Arrays.toString(int[]) to get a String. Like,
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
I tested the above like
public static void main(String[] args) {
int[] t = { 1, 2, 3, 4 };
printArray(t);
swapPairs(t);
printArray(t);
}
And I got
[1, 2, 3, 4]
[2, 1, 4, 3]

After almost breaking my computer several times, here's the actual working code:
public static void swapPairs(int[] a){
int len=a.length;
if(len%2 ==0){
for(int i=0; i<len; i=i+2){
int c=a[i]+a[i+1];
a[i]=c-a[i];
a[i+1]=c-a[i+1];
}
}
if(len%2 !=0){
for(int j=0; j<len-1; j=j+2){
int c=a[j]+a[j+1];
a[j]=c-a[j];
a[j+1]=c-a[j+1];
}
a[len-1]=a[len-1];
}
}
public static void printArray(int[] a){
int len=a.length;
for(int i=0;i<len;i++)
System.out.print(a[i]+" ");
}

public static void swapPairs(int[] arr){
int length = arr.length%2 == 0? arr.length : arr.length-1;
for(int i=0; i<length; i=i+2) {
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
// print the array
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}

public static void swapPairs(int[] a){
int len = a.length - a.length % 2; // if len is odd, remove 1
for(int i = 0; i < len; i += 2) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
public static void printArray(int[] a){
System.out.println(Arrays.toString(a));
}
public static void main(String[] args) {
int[] iArr1 = {10, 20, 30, 40, 50};
int[] iArr2 = {10, 20, 30, 40, 50, 60};
swapPairs(iArr1);
swapPairs(iArr2);
printArray(iArr1); // [20, 10, 40, 30, 50]
printArray(iArr2); // [20, 10, 40, 30, 60, 50]
}

final int[] number = new int[] { 1, 2, 3, 4, 5, 6, 7 };
int temp;
for (int i = 0; i < number.length; i = i + 2) {
if (i > number.length - 2) {
break;
}
temp = number[i];
number[i] = number[i + 1];
number[i + 1] = temp;
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j]);
}

import java.util.Scanner;
public class SwapEveryPair {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
for (int i = 0; i < (arr.length - 1); i += 2) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
for(int i=0; i< arr.length; i++){
System.out.println(" " + arr[i]);
}
}
}``

I think this should work,
public static void swapAlternate(int[] input){
for(int i=0;i<input.length - 1; i+=2){
int temp = input[i];
input[i] = input[i+1];
input[i+1] = temp;
}
}

Related

merging 3 sorted arrays

public class array12 {
static void merge_sort(int A[], int start, int end) {
if (end - start > 1) {
int middle1 = (2 * start + end + 1) / 3 - 1;
int middle2 = 2 * middle1 - start + 1;
merge_sort(A, start, middle1);
merge_sort(A, middle1 + 1, middle2);
merge_sort(A, middle2 + 1, end);
merge(A, start, middle1, middle2, end);
}
}
static void merge(int[] x, int start, int middle1, int middle2, int end) {
int n1 = middle1 - start + 1;
int n2 = middle2 - middle1;
int n3 = end - middle2;
int left[] = new int[n1]; // defining and initialising three arrays .
int mid[] = new int[n2];
int right[] = new int[n3];
for (int i = 0; i < left.length; i++) {
left[i] = x[i + start];
}
for (int i = 0; i < mid.length; i++) {
mid[i] = x[i + middle1 + 1];
}
for (int i = 0; i < right.length; i++) {
right[i] = x[i + middle2 + 1];
}
int i = 0;
int j = 0;
int k = 0;
int c = start;
// finding minimum element from the three arrays .
while (i < n1 && j < n2 && k < n3) {
if (left[i] <= mid[j] && left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else if (mid[j] <= left[i] && mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only two arrays are left to be compared
while (i < n1 && j < n2) {
if (left[i] <= mid[j]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = mid[j];
j++;
c++;
}
}
while (j < n2 && k < n3) {
if (mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
while (i < n1 && k < n3) {
if (left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only single array is left out of left[] , mid[] and right[].
while (i < n1) {
x[c] = left[i];
i++;
c++;
}
while (j < n2) {
x[c] = mid[j];
j++;
c++;
}
while (k < n3) {
x[c] = right[k];
k++;
c++;
}
System.out.println("");
// printing array elements after every merge operation .
for (int e = 0; e < x.length; e++) {
System.out.print(x[e] + " ");
}
}
public static void main(String[] args) {
int[] x = new int[9];
for (int i = 0; i < x.length; i++) {
x[i] = x.length - i;
}
System.out.println("initial array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
System.out.println("");
merge_sort(x, 0, x.length - 1);
System.out.println("");
System.out.println("");
System.out.println(" sorted array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
}
I am trying to merge 3 sorted arrays . I have been able to develop code for array size equal to power of 3 . I am unable to implement it with some other array size . I have tried to change values of middle1 and middle2 but am experiencing serious trouble . Setting their values is the main concern . Merging step is quite simple and is not causing problems .
What changes are required in my code so that it may work for any array size ? Can it be implemented using this approach ? I dont want size of any of the three arrays , left[] , mid[] and right[] to be zero at any time .
Please help .
Here's a similar answer to YCF_L's, but simplified (still uses Java 8):
public static int[] sortMultipleArrays(int[]... arrays) {
return Arrays.stream(arrays)
.flatMapToInt(Arrays::stream)
.sorted()
.toArray();
}
Output:
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
I don't follow your merge code. It seems overly complicated.
Here is a method for merging an unlimited number of sorted arrays, each a varying size.
private static int[] mergeSortedArrays(int[]... arrays) {
int totalLen = 0;
for (int[] arr : arrays)
totalLen += arr.length;
int[] idx = new int[arrays.length];
int[] merged = new int[totalLen];
for (int i = 0; i < totalLen; i++) {
int min = 0, minJ = -1;
for (int j = 0; j < arrays.length; j++)
if (idx[j] < arrays[j].length)
if (minJ == -1 || min > arrays[j][idx[j]]) {
min = arrays[j][idx[j]];
minJ = j;
}
merged[i] = min;
idx[minJ]++;
}
return merged;
}
Test
int[] a = { 3, 5, 9, 13, 17, 21 };
int[] b = { 2, 10, 20 };
int[] c = { 1, 7, 12, 24 };
int[] d = { 6 };
int[] merged = mergeSortedArrays(a, b, c, d);
System.out.println(Arrays.toString(merged));
Output
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
If using class "Integer" instead of primitive int is not a problem you can use this, basically first do the merge and after sort them: you can do the call Arrays.sort even in the same method and call it mergeAndSort, if you want...
import java.util.Arrays;
public class Main {
public static Integer[] merge(Integer[]... arrays) {
int count = 0;
for (Integer[] array : arrays) {
count += array.length;
}
Integer[] mergedArray = (Integer[]) java.lang.reflect.Array.newInstance(arrays[0][0].getClass(), count);
int start = 0;
for (Integer[] array : arrays) {
System.arraycopy(array, 0, mergedArray, start, array.length);
start += array.length;
}
return mergedArray;
}
public static void main(String[] args) {
Integer[] array1 = {3, 5, 6, 7, 78, 100};
Integer[] array2 = {5, 6, 7, 8, 9};
Integer[] array3 = {2, 6, 7};
Integer[] merged1 = merge(array1, array2);
Arrays.sort(merged1);
Integer[] merged2 = merge(array1, array2, array3);
Arrays.sort(merged2);
printArray(merged1);
printArray(merged2);
}
public static void printArray(Integer[] x) {
System.out.println("--ToString--");
for (Integer var : x) {
System.out.println(var);
}
System.out.println("----");
}
}

Programming Issue in my counting sort algo

Please let me know the issue i have in this short code. I tried to follow the algo from the book and convert it into a program but have done some error in the process. Its throwing arrayoutofbounds exception
Algo which i tried to follow is bellow:
countingsort(a,b,k)
1)let c[0..k] be a new array
2)for i =0 to k
3) c[i]=0;
4)for j=1 to a.length
5) c[a[j]]=c[a[j]]+1
6)for i = i to k
c[i] = c[i] + c[i-1]
7)for j=a.length downto 1
b[c[a[j]]]= a[j]
c[a[j]] = c[a[j]]-1
public class CountingSort {
public static void main(String[] args) {
int[] array_A = {6, 0, 2, 0, 1, 3, 4, 6, 1, 3, 2};
int[] array_B = new int[array_A.length];
int k = 6;
countingSort(array_A,array_B,k);
//System.out.println(array_B);
}
public static void countingSort(int[] A, int[] B, int k){
int[] C = new int[k+1];
for(int i = 0; i<=k; i++){
C[i] = 0;
}
for(int j = 0; j<A.length; j++){
C[A[j]] = C[A[j]] + 1;
}
for(int i = 1; i<=k; i++){
C[i] = C[i] + C[i-1];
}
for(int j = A.length-1; j>=1; j--){
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
System.out.println(Arrays.toString(B));
}
}
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at importantPrograms.CountingSort.countingSort(CountingSort.java:22)
at importantPrograms.CountingSort.main(CountingSort.java:11)
Here is the modified code that worked for me.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] array_A = {6, 0, 2, 0, 1, 3, 4, 6, 1, 3, 2};
int[] array_B = new int[array_A.length];
int k = 6;
countingSort(array_A,array_B,k);
System.out.println(Arrays.toString(array_B));
}
public static void countingSort(int[] A, int[] B, int k){
int[] C = new int[k+1];
for(int i = 0; i<=k; i++){
C[i] = 0;
}
for(int j = 0; j<A.length; j++){
C[A[j]] ++;
}
for(int i = 1; i<=k; i++){
C[i] += C[i-1];
}
for(int j = A.length-1; j>=0; j--){
B[--C[A[j]]] = A[j];
}
}
}
Ideally, instead of hard-coding the max value (6), you would find the max programmatically and size your count array accordingly. Such as
In main method
countingSort(array_A,array_B,max(array_A));
Max method
public int max(int[] arr){
int m = 0;
for(int i : arr){
if(i>m){
m = i;
}
}
return m;
}
Change
C[A[j]] = C[A[j] + 1]; to C[A[j]] = C[A[j]] + 1; because you are supposed to count the number of particular number occurrence.
I have no clue what you are doing but there is only a little mistake in your second for loop.
Change j<A.length to j<C.length

Java negative counting?

i need a simple negative number counter in a basic bubble sort.. i have this code
public static void printArray(int[] a) {
System.out.print("Tvoj niz je: ");
for (int k = 0; k < a.length; ++k){
System.out.println();
System.out.println ( a[k] );
}
System.out.println();
}
public static void bubbleSort(int[] a) {
int neg;
int temp;
for (int i = 0; i < a.length; ++i) {
for (int 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;
}
}
}
}
public static void main(String[] args) {
int[] a = {7, 4, 11, -3, 1, -2};
bubbleSort(a);
printArray(a);
now i need to have on output the number of negative numbers in array in this case number 2, because i have -3 and -2... :)
int negCount = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] < 0) {
negCount++;
}
}
negCount will hold the negative integers count.

Need help on sorting an array -- a new programmer

I am just sorting an array and need some advice on the sorting and I also need help printing the array after I have sorted it. Also no, I do not want to use the Arrays utility.
Code:
package Sort;
public class SortCode {
static int[] intArray = {
12, 34, 99, 1, 89,
39, 17, 8, 72, 68};
int j = 0;
int i = 0;
void printArray(int[] arrayInts) {
System.out.println("Values before sorting:");
System.out.println("Index" + "\tValue");
for (; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} //for (int j)
} //void printArray
void sortArray() {
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
int i;
int k;
for (i = 0; i < intArray.length; i++) {
for (k = 0; k > intArray.length; k++) {
if (intArray[i] > intArray[k]) {
int firstNum = intArray[i];
int secondNum = intArray[k];
intArray[i] = secondNum;
intArray[k] = firstNum;
} //if
} //for
} //for
} //void sortArray
} //class BranchCode
Change sign > for < inside for (k = 0; k > intArray.length; k++) {
Probably it should help you
You would be able to find different sorting implementation on mathbits http://mathbits.com/MathBits/Java/arrays/Sorting.htm .
Here is better example of bubble sort .
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
This might help as well Java: Sort an array
Example to use code
public class SortExample {
int[] intArray = { 12, 34, 99, 1, 89, 39, 17, 8, 72, 68 };
public void printArray(int[] arrayInts) {
for (int j = 0; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} // for (int j)
} // void printArray
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
public void process() {
System.out.println("Values before sorting:");
System.out.println("Index \tValue");
printArray(intArray);
bubbleSort(intArray);
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
printArray(intArray);
}
public static void main(String[] args) {
SortExample example = new SortExample();
example.process();
}
}

Generating permutations of an int array using java -- error

I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.
This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}
check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}
import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}
I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}
A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f

Categories