Shift array elements by n posisition - java

I've got method to move elements in array, move to right work fine, move to left work incorrect. Method get two incoming parameters:
1st: array
2nd: int variable to move element on this int parameter.
Here is my method:
private static int[] arrShift(int[]arr, int count) {
if (count >= 0) {
for (int i = 0; i < count; i++) {
int temp = arr[arr.length - 1];
for (int j = arr.length - 2; j > -1; j--) {
arr[j + 1] = arr[j];
}
arr[0] = temp;
}
}
if (count < 0){
count *=-1;
int temp = arr[0];
for (int i = 0; i < count; i++) {
for (int j = 0; j < arr.length -1; j++) {
arr[j] = arr[j + 1];
}
}
arr[0] = temp;
}
return arr;
}
How shift elements to left?

This should work like a charm :)
private static int[] arrShift(int[]arr, int count) {
if (count >= 0) {
for (int i = 0; i < count; i++) {
int temp = arr[arr.length - 1];
for (int j = arr.length - 2; j > -1; j--) {
arr[j + 1] = arr[j];
}
arr[0] = temp;
}
}
if (count < 0){
count *=-1;
for (int i = 0; i < count; i++) {
int temp = arr[0];
for (int j = 0; j < arr.length -1; j++) {
arr[j] = arr[j + 1];
}
arr[arr.length - 1] = temp;
}
}
return arr;
}

Related

Find the number of distinct triplets sums to a given integer

You have been given a random integer array/list(ARR) and a number X. Find and return the number of distinct triplet(s) in the array/list which sum to X.
I have written this code:
public class Solution {
public static void merge(int arr[], int lb, int mid, int ub) {
int n1 = mid - lb + 1;
int n2 = ub - mid;
int arr1[] = new int[n1];
int arr2[] = new int[n2];
for (int i = 0; i < n1; i++)
arr1[i] = arr[lb + i];
for (int j = 0; j < n2; j++)
arr2[j] = arr[mid + 1 + j];
int i = 0, j = 0;
int k = lb;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j])
arr[k] = arr1[i++];
else
arr[k] = arr2[j++];
k++;
}
while (i < n1)
arr[k++] = arr1[i++];
while (j < n2)
arr[k++] = arr2[j++];
}
public static void mergeSort(int arr[], int lb, int ub) {
if (lb < ub) {
int mid = lb + (ub - lb) / 2;
mergeSort(arr, lb, mid);
mergeSort(arr, mid + 1, ub);
merge(arr, lb, mid, ub);
}
}
public static int tripletSum(int[] arr, int num) {
mergeSort(arr, 0, arr.length - 1);
int n = arr.length;
int count = 0;
for (int i = 0; i < n - 2; i++) {
int sum = num - arr[i];
int j = i + 1;
int k = n - 1;
while (j < k) {
if (arr[j] + arr[k] == sum) {
count++;
k--;
} else if (arr[j] + arr[k] > sum) {
k--;
} else
j++;
}
}
return count;
}
}
Input array was - 1 3 3 3 3 3 3
Input num = 9
Output Generated - 10
Expected output - 20
Help me out with this I'm trying to find the solution for many hours. Also, the time complexity of the program should not exceed O(n²).
The given code works fine for all test cases.
import java.util.Arrays;
public class Solution {
public static int tripletSum(int[] arr, int num) {
Arrays.sort(arr);
int n = arr.length;
int Numtripletsum = 0;
for(int i=0;i<n;i++)
{
int pairSumFor = num - arr[i];
int numPairs = pairSum(arr, (i+1), (n-1), pairSumFor);
Numtripletsum+=numPairs;
}
return Numtripletsum;
}
private static int pairSum(int[] arr, int startIndex, int endIndex, int num ){
int numPair = 0;
while(startIndex < endIndex){
if(arr[startIndex] + arr[endIndex] < num){
startIndex++;
}
else if(arr[startIndex] + arr[endIndex] > num){
endIndex--;
}
else
{
int elementAtStart = arr[startIndex];
int elementAtEnd = arr[endIndex];
if(elementAtStart == elementAtEnd){
int totalElementsFromStartToEnd = (endIndex - startIndex) + 1;
numPair += (totalElementsFromStartToEnd * (totalElementsFromStartToEnd -1) /2);
return numPair;
}
int tempStartIndex = startIndex + 1;
int tempEndIndex = endIndex - 1;
while(tempStartIndex <= tempEndIndex && arr[tempStartIndex] == elementAtStart){
tempStartIndex+=1;
}
while(tempEndIndex >= tempStartIndex && arr[tempEndIndex] == elementAtEnd){
tempEndIndex-=1;
}
int totalElementsFromStart = (tempStartIndex - startIndex);
int totalElementsFromEnd = (endIndex - tempEndIndex);
numPair += (totalElementsFromStart * totalElementsFromEnd);
startIndex = tempStartIndex;
endIndex = tempEndIndex;
}
}
return numPair;
}
}
I did it in this way, hope I understood it well.
public static int tripletSum(int[] arr, int num) {
int loops = 0; // just to check the quality of the code
int counter = 0;
for (int i1 = 0; i1 < arr.length - 2; i1++) {
for (int i2 = i1 + 1; i2 < arr.length - 1; i2++) {
for (int i3 = i2 + 1; i3 < arr.length; i3++) {
loops++;
if (arr[i1] + arr[i2] + arr[i3] == num) {
counter++;
}
}
}
}
// Check for not exceeding O(n^2)
if (loops <= arr.length * arr.length) {
System.io.println("Well done");
} else {
System.io.println("Too many cycles");
}
return counter;
}
I iterate from "left" to "right" over the array and walking more and more to the "right".
1st, 2nd, 3rd
1st, 2nd, 4th
...
1st, 2nd, nth
2nd, 3rd, 4th
2nd, 3rd, 5th
...
2nd, 3rd, nth
.
.
.
nth - 2, nth - 1, nth
I iterated 35 times, but could iterate 7^2 = 49 times --> "Well done"
You missed one loop. The fixed code:
public static int tripletSum(int[] arr, int num) {
//Your code goes here
mergeSort(arr, 0, arr.length - 1);
int n = arr.length;
int count = 0;
for (int i = 0; i < n - 2; i++) {
int sum = num - arr[i];
for (int j = i+1; j < n-1; j++) {
int k = n-1;
while (j < k) {
if (arr[j] + arr[k] == sum) {
count++;
k--;
} else if (arr[j] + arr[k] > sum) {
k--;
} else {
j++;
}
}
}
}
return count;
}
OK, then optimized version:
public static int tripletSum(int[] arr, int num) {
//Your code goes here
mergeSort(arr, 0, arr.length - 1);
int n = arr.length;
int count = 0;
for (int i = 0; i < n - 2; i++) {
int sum = num - arr[i];
int maxK = n - 1;
for (int j = i + 1; j < n - 1; j++) {
int k = maxK;
while (j < k) {
if (arr[j] + arr[k] == sum) {
count++;
k--;
} else if (arr[j] + arr[k] > sum) {
k--;
maxK--;
} else {
j++;
}
}
}
}
return count;
}

Time complexity of two different bubble sort method with the same iterations

I was implementing a bubble sort algorithm and I was confused whether the two below given java methods will give the same time complexity or will it be different:
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
This method had O(N^2) Time complexity - I am sure about it.
void bubbleSort(int arr[])
{
int n = arr.length;
int i=0,j=0;
while(i<n-1)
{
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
j++;
if(j==n-i-1)
{
j=0;
i++;
}
}
I am not sure about this one as it does the same iteration using single loop ?
Both implementations have the same complexity, which is easy to see by comparing the number of their iterations. Let's add counters to places where iterations occur and compare their values after sorting:
class Main {
private static int count1 = 0, count2 = 0;
public static void main(String[] args) {
int[] array1 = new int[]{1, 6, -4, 0, 12, -8}, array2 = new int[]{1, 6, -4, 0, 12, -8};;
bubbleSort1(array1);
bubbleSort2(array2);
System.out.println(count1);
System.out.println(count2);
}
private static void bubbleSort1(int arr[]) {
int n = arr.length;
for (int i = 0; i < n-1; ++i) {
++count1;
for (int j = 0; j < n-i-1; ++j) {
++count1;
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
private static void bubbleSort2(int arr[]) {
int n = arr.length;
int i = 0, j = 0;
while (i < n - 1) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
++j;
++count2;
if (j == n - i - 1) {
j = 0;
++i;
++count2;
}
}
}
}
Output:
20
20
It is not the number of cycles that is important in complexity assessment, but the algorithm itself, and here it is the same O(n^2).

How to fix the "NegativeArraySizeException" on my merge sort code?

If the array to be sorted is 10 elements and above, I get the NegativeArraySizeException. It says it's on this line of code "int R[] = new int[n2];" , how can I fix this?
If you were wondering why my merge sort doesn't have any other methods, my professor specifically asked for a merge sort within just the main method. This merge sort is the iterative version because I couldn't compress the recursive version to main method only.
public static void main(String[] args)
{
int arr[] = {100,99,98,97,96,95,94,93,92,93};
int n = arr.length;
int curr_size;
int left_start;
for (curr_size = 1; curr_size <= n-1;
curr_size = 2*curr_size)
{
for (left_start = 0; left_start < n-1;
left_start += 2*curr_size)
{
int mid = left_start + curr_size - 1;
int right_end = Math.min(left_start
+ 2*curr_size - 1, n-1);
int i, j, k;
int n1 = mid - left_start + 1;
int n2 = right_end - mid;
/* create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
/* Copy data to temp arrays L[]
and R[] */
for (i = 0; i < n1; i++){
L[i] = arr[left_start + i];
}
for (j = 0; j < n2; j++){
R[j] = arr[mid + 1+ j];
}
i = 0;
j = 0;
k = left_start;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1){
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
}
System.out.printf("\nSorted array is \n");
int i= 0;
for (i=0; i < n; i++){
System.out.print(arr[i]+ " ");
}
}
}
I think I've fixed it. Certainly works for given array.
Try
int mid = Math.min(left_start + curr_size - 1, n-1);
instead of
int mid = left_start + curr_size - 1;

I was trying to implement insertionsort method byt i don't get a write array sorting

My array is {8,3,5,9,2} and I get {3,5,9,2}
public static void insertionsort(int[] a) {
for (int i = 1; i < a.length; i++) {
int value = a[i];
// int c=0;
for (int j = i - 1; value < a[j + 1] && j >= 0; j--) {
int temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
// c++;
}
}
}
Could some one help me figure out the problem in my code
.
You never enter the second for loop.
At start i=1 j=i-1 value=3 a[j+1]=3
value < a[j + 1] is like 3<3 so it is always false.
Try this:
int n = a.length;
for (int i=1; i<n; ++i)
{
int temp = a[i];
int j = i-1;
while (j >= 0 && a[j] > temp)
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}

My code that determines if two arrays are permutations always returns false, why?

I've written this to sort two arrays and then compare the values to see if they're the same, but it always returns false, and I can't figure out why.
It is supposed to find if two arrays are permutations of each other.
public class Permutations {
public static void main(String[] args) {
int[] a = {1,4,6,7,8,34};
int[] b = {34,6,8,1,4,7};
System.out.println(arePermutations(a, b));
}
public static boolean arePermutations(int[] a, int[] b)
{
int count = 0;
int temp = 0;
if(a.length == b.length)
{
for(int i=0; i<a.length-1; i++)
for(int j=0; j<a.length-1; j++)
if(a[i] > a[j+1] && i>j+1)
{
temp = a[i];
a[i] = a[j+1];
a[j+1] = temp;
}
{
for(int i=0; i<b.length-1; i++)
for(int j=0; j<b.length-1; j++)
if(b[i] > b[j+1] && i>j+1)
{
temp = b[i];
b[i] = b[j+1];
b[j+1] = temp;
}
}
for(int i=0; i<a.length; i++)
if(a[i] == b[i])
{
count++;
}
if (count == a.length)
{
return true;
}
else return false;
}
else return false;
}
}
The problem is in the implementation of the bubble sort. Change your sorting loops to the following:
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b.length - 1; j++) {
if (b[j] > b[j + 1]) {
temp = b[j];
b[j] = b[j + 1];
b[j + 1] = temp;
}
}
}
This code works because a bubble sort just swaps adjacent elements if they need swapping, but needs to run through the entire array multiple times (up to the number of items in the array) to get all the items into the correct position.

Categories