Right shift content of int array to num - java

I tried:
public static void main(String[] args) {
int array [] = {2, 5, 1, 4, 7, 9, 0};
for (int i = 0; i < array.length-2; i++) {
swapNum(array[i], array[i+2]);
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
public static void swapNum(int a, int b){
int tmp = a;
a = b;
b = tmp;
}
But found that it is not swapping values. Then I took help from here
https://codereview.stackexchange.com/questions/86016/left-shifting-an-array-of-ints
public void anotherTry() {
int nums [] = {4, 5, 2, 1, 6, 8};
for (int i = 0, start = 0; i < nums.length; i++) {
if (i == 0)
start = nums[i];
if (i == (nums.length - 1)) {
nums[i] = start;
break;
}
nums[i+2] = nums[i];
System.out.println(Arrays.toString(nums));
}
System.out.println(Arrays.toString(nums));
}
Its gives array out of bound of exception.
Where I am wrong?
Role of start variable. If start always will be equal to nums[i]?

You can't swap values like that in Java. However, since you are using an array and want to swap values within the array, you can rewrite your swap method to work with indexes:
public static void main(String[] args) {
int array [] = {2, 5, 1, 4, 7, 9, 0};
for (int i = 0; i < array.length-2; i++) {
swapNum(array, i, i+2);
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
public static void swapNum(int[] values, int i, int j){
int tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}

Related

JAVA/Selection sort : the console shows different results from what I've entered

I'm learning how to implement selection sort.
What I expected from the code is an ascending order output, like: {1,3,4,5,6,7,9}
But the console showed: 9, 4, 1, 6, 5, 3, 7, 9, 7, 1, 4, 5, 3, 6, 9, 7, 6, 1, 4, 3, 5, 9, 7, 6, 5, 1, 3, 4, 9, 7, 6, 5, 4, 1, 3, 9, 7, 6, 5, 4, 3, 1
What am I supposed to change to get the correct result?
This is my code:
public static void main(String[] args) {
int[]arr = {4,6,1,9,5,3,7};
for(int i = 0; i<arr.length-1; i++) {
for(int j = i+1; j<arr.length; j++) {
if(arr[i]<arr[j]) {
int a=arr[i];
arr[i]=arr[j];
arr[j]=a;
}
}
for (int b = 0; b <arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
You are printing the array while you are doing the sorting. Instead, print the array when you are done with the sorting -
public static void main(String[] args) {
int[] arr = {4, 6, 1, 9, 5, 3, 7};
for (int i = 0; i < arr.length - 1; i++) { // first loop
for (int j = i + 1; j < arr.length; j++) { // nested loop
if (arr[i] < arr[j]) { // if condition
int a = arr[i];
arr[i] = arr[j];
arr[j] = a;
} // if condition ends
} // nested loop ends
} // first loop ends
// Now the array is sorted, it's good to print.
for (int b = 0; b < arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
There is one more catch. Though your sorting would work, your implementation is not really selection sort. It's bubble sort implementation. The key difference is, in selection sort you need to find the min value and place it in the ith position for every i. So you only swap once per iteration. In bubble sort, we swap repeatedly like you did.
Also, as pointed out in the comment, for ascending order, you have to flip to condition for swapping. So the correct implementation would be -
public static void main(String[] args) {
int[] arr = {4, 6, 1, 9, 5, 3, 7};
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
for (int b = 0; b < arr.length; b++) {
System.out.print(arr[b] + ", ");
}
}
There is an easier way with Arrays.sort(arr)
public static void main(String[] args) {
int[] arr = {4,6,1,9,5,3,7};
Arrays.sort(arr);
System.out.print(Arrays.toString(arr));
}
}
Selection Sort - java code
class selectionsort{
public static void sort(int[] arr){
int temp,min;
for(int i=0;i<arr.length;i++)
{
min=i;
for(int j=i+1;j<arr.length;j++)
{
if(arr[min]>arr[j])
{
min=j;
}
}
temp=arr[min];
arr[min]=arr[i];
arr[i]=temp;
}
}
public static void main(String [] args){
int ar[]={4,6,1,9,5,3,7};
sort(ar);
System.out.print("After sort :");
for(int j=0;j<ar.length;j++){
System.out.print(ar[j]+" ");
}
}
}

Sorting list of numbers

I am trying to sort a list of numbers from smallest to the biggest and print it. I've tried two things:
1.
public class Sorter {
public static void main(String[] args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
int[] sorted = new int[numbers.length];
for (int a = 0; a < numbers.length; a++) {
int check = 0;
for (int b = 0; b < numbers.length; b++) {
if (numbers[a] < numbers[b]) {
check++;
}
}
sorted[check] = numbers[a];
}
for (int c = numbers.length - 1; c >= 0; c--) {
System.out.print(sorted[c] + ", ");
}
}
}
and this thing works, but won't work with repeated values, so I tried this other thing
public class Sortertwo {
public static void main(String[] args) {
int[] numinput = {3, 2, 1, 4, 7, 3, 17, 5, 2, 2, -2, -4};
int[] numsorted = new int[numinput.length];
int n = 0;
for (; n < numinput.length; ) {
for (int b = 0; b < numinput.length; b++) {
int check = 0;
for (int c = 0; c < numinput.length; c++) {
if (numinput[b] <= numinput[c]) {
check++;
}
}
if (check >= (numinput.length - n) && numinput[b] != 0) {
numsorted[n] = numinput[b];
numinput[b] = 0;
n++;
}
if (n >= (numinput.length)) {
break;
}
}
}
for (int g = 0; g < numinput.length; g++) {
System.out.print(numsorted[g] + ", ");
}
}
}
Where it relies on the thing that once the number from the first array is used (the smallest one is found), it has to be ignored when the program goes through the array next time around.
I tried to assign it like null value, but it doesn't work, so I assigned it to zero and then ignore it, which is a problem, because the list cant have a zero in it.
Is there any like better way to go about it? Thanks.
You can always use:
Arrays.sort(numbers);
If you want to use your first method then change this:
if (numbers[a] < numbers[b])
{
check++;
}
to:
if (numbers[a] <= numbers[b])
{
check++;
}
Unless this is homework, using Arrays.sort as the comments suggest, should be the way to go
import java.util.Arrays;
public class S {
public static void main(String ... args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
Prints:
[-2, 0, 1, 2, 3, 5, 7, 8, 15]

How solve: Array type expected, found int? in bubble sort using array not the list

I have a task where I need to do a Bubble Sort program. I have to use array, not the list. I receive couple of errors, where it says that
"Array type expected, found int"
public class BubbleSort {
public static void main(String[] args) {
int array[] = {9, 7, 5, 8, 1, -5};
System.out.println(Arrays.toString(sort(array)));
}
public static int[] sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (array[j] > array[j + 1]) {
}
return swapElementsInArray(array);
}
private static void swapElementsInArray(int[] array, int indexOfFirstElement, int indexOfSecondElement) {
if (array[indexOfSecondElement] > array[indexOfSecondElement + 1]) {
array [] = indexOfFirstElement[indexOfSecondElement];
indexOfFirstElement[indexOfSecondElement] = indexOfFirstElement[indexOfSecondElement + 1];
indexOfFirstElement[indexOfSecondElement + 1] = array;
}
}
}
I need to keep this structure, it's my tutor requirement to use these long names. And I cannot modify methods.
so the method was wrong about what to swap and the error was wrong attribution - int into array.
Here is your example working:
public static void main(String[] args) {
int[] array = {9, 7, 5, 8, 1, -5};
System.out.println(Arrays.toString(sort(array)));
}
public static int[] sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i+1; j < n; j++) {
if (array[i] > array[j]) {
swapElementsInArray(array, i, j);
}
}
}
return array;
}
private static void swapElementsInArray(int[] array, int indexOfFirstElement, int indexOfSecondElement) {
if (array[indexOfFirstElement] > array[indexOfSecondElement]) {
int oldVal = array[indexOfFirstElement];
array[indexOfFirstElement] = array[indexOfSecondElement];
array[indexOfSecondElement] = oldVal;
}
}
This prints:
[-5, 1, 5, 7, 8, 9]

Using an array to find the multiples of two ints

Im a programming student and im having alot of trouble with this question:
"complete a static method multiplesOf which takes two int parameters, number and count. The method body must return an int array containing the first count multiples of number. For example,
multiplesOf(5, 4) should return the array { 5, 10, 15, 20 }
multiplesOf(11, 3) should return the array { 11, 22, 33 }
multiplesOf(1, 15) should return the array { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
You must not use System.out.print or System.out.println in your method."
This is my current code:
public static void main(String[] args) {
multiplesOf(5,4);
}
public static int[] multiplesOf (int number, int count) {
int[] a = new int[count];
a[0]= number;
for(int i = 0; i<count; i++) {
a[i] = (a[i]*count);
}
return a;
}
Ive been trying to figure out why the array "a" still only has the values 0,1,2,3
Try:
public static int[] multiplesOf(int number, int count) {
int[] a = new int[count];
for(int i = 1; i <= count; i++) {
a[i - 1] = number * i;
}
return a;
}
a[0] = number;
for(int i = 1; i<count; i++)
{
a[i] = (i+1)*number;
}
try this
public static int[] multiplesOf (int number, int count)
{
int[] a = new int[count];
a[0] = number;
for(int i = 1; i<count; i++)
{
a[i] = number * (i + 1);
}
return a;
}
output
[5, 10, 15, 20]
public static int[] multiplesOf(int number, int count) {
int[] a = new int[count];
for (int i = 0; i < count; i++) {
a[i] = (number * (i+1));
}
return a;
}
use this
public static int[] multiplesOf (int number, int count) {
int[] a = new int[count];
for(int i = 1; i<=count; i++) {
//a[i-1] beacuse we started iterating array at i=1
a[i-1] = (i*number);
}
return a;
}
multiplesOf(5, 4) returns -> the array { 5, 10, 15, 20 }

Java - Merge Two Arrays without Duplicates (No libraries allowed)

Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).

Categories