I have some code that I've compiled and ran. It is suppose to sort the values from smallest to greatest. Can someone help me find what is going on in the code and not making it sort correctly? I get these numbers
-9 -3 -1 1 6 7 83 19 2 6 4 6 32 66
Can someone help me and tell me what is wrong with the code? Thank you!
int myArray[] = {1, 6, -1, 7, 83, 19, -3, 6, 2, 4, 6, 32, 66, -9};
int n = myArray.length;
myArray = doop(myArray);
for (int i = 0; i < n; i++) {
System.out.println(myArray[i]);
}
private static int[] doop(int[] myArray) {
int n = myArray.length;
int swap;
for (int i = n - 1; i >= 0; i--) {
int j = i;
int min = myArray[i];
while ((j > 0) && (myArray[j - 1] < min)) {
myArray[j] = myArray[j - 1];
j = j - 1;
}
myArray[j] = min;
}
return myArray;
}
In bubble sort you have to compare the only the adjacent elements and traverse the array. Repeating this n-1 times , your array gets sorted and so correct code is:
private static int[] doop(int[] myArray)
{
int n = myArray.length;
for (int i = n - 1; i >= 0; i--)
{
for(int j=n-1;j>0;j--)
{
if(myArray[j]<myArray[j-1])
{
//swapping the elements
myArray[j]=myArray[j]^myArray[j-1];
myArray[j-1]=myArray[j]^myArray[j-1];
myArray[j]=myArray[j]^myArray[j-1];
}
}
}
return myArray;
}
int myArray[] = {1, 6, -1, 7, 83, 19, -3, 6, 2, 4, 6, 32, 66, -9};
int n = myArray.length;
myArray = doop(myArray);
for (int i = 0; i < n; i++) {
System.out.println(myArray[i]);
}
}
private static int[] doop(int[] myArray) {
int n = myArray.length;
int swap;
for (int i = n - 1; i >= 0; i--) {
int j = i;
int min = myArray[i];
while ((j > 0) && (myArray[j - 1] < min)) {
myArray[j] = myArray[j - 1];
j = j - 1;
myArray[j] = min;
}
}
return myArray;
}
Related
I want to print out an increasing number of elements in my array per line but I'm not sure how I could do it.
public static void main(String[] args) {
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
System.out.println(Arrays.toString(x));
}
I would like my output to look like:
[1]
[2, 3]
[4, 5, 6]
etc...
instead of what I get right now which is
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
I'm really new to java so any tips would really be appreciated, thanks.
Add this below your code.
for (int i = 0, ctr = 0; i < x.length; ctr++) {
System.out.print("[ ");
for (int j = 0; j <= ctr; i++) {
System.out.print(x[i]);
j++;
if (j <= ctr) {
System.out.print(" ,");
}
}
System.out.println(" ]");
}
This method does not require storage
int start = 1;
int count = 1;
int outer = 6;
for (int y = 0; y < outer; y++) {
System.out.print ("[");
int x = start;
for (; x < start + count; x++) {
System.out.print (x);
if (x < start + count - 1)
System.out.print(",");
}
System.out.println ("]");
count++;
start = x;
}
result
[1]
[2,3]
[4,5,6]
[7,8,9,10]
[11,12,13,14,15]
[16,17,18,19,20,21]
You can use this code
int[] x = new int[21];
for (int i = 0; i < x.length; i++) {
x[i] = i + 1;
}
int start = 0, len = 1;
while(start + len <= x.length) {
int[] newArray = Arrays.copyOfRange(x, start, start + len);
System.out.println(Arrays.toString(newArray));
start += len;
len++;
}
Using two loops you can achieve the result, the outer loop will create an empty array with each iteration and the inner one will populate it with numbers. Also using a third variable to keep track of the last number generated.
public static void main(String[] args) {
int n = 21;
int lastNumber = 0;
int x[] = null;
for(int j = 0; j< n; j++) {
x = new int[j];
for (int i = 0, k = lastNumber; i< j; i++,k++) {
x[i] = k + 1;
}
if(x.length != 0){
lastNumber = x[x.length - 1];
System.out.println(Arrays.toString(x));
}
}
}
Output:
[1]
[2, 3]
[4, 5, 6]
[7, 8, 9, 10]
[11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21]
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("----");
}
}
I have 10 numbers in a vector container contains: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. And I want n numbers in a group, for example:
n = 3
[1,2,3], [4,5,6], [7,8,9], [10]
[2,3,4], [5,6,7], [8,9,10], [1]
Is there an algorithm to find all the combinations?
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
List<int[]> subsets = new ArrayList<>();
int[] s = new int[k]; // here we'll keep indices
// pointing to elements in input array
if (k <= input.length) {
// first index sequence: 0, 1, 2, ...
for (int i = 0; (s[i] = i) < k - 1; i++);
subsets.add(getSubset(input, s));
for(;;) {
int i;
// find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
if (i < 0) {
break;
}
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(input, s));
}
}
System.out.println();
for(int i = 0; i < subsets.size();i++) {
int[] result = subsets.get(i);
for(int j = 0; j < result.length; j++) {
System.out.print(result[j]+" ");
}
System.out.println();
}
}
int[] getSubset(int[] input, int[] subset) {
int[] result = new int[subset.length];
for (int i = 0; i < subset.length; i++)
result[i] = input[subset[i]];
return result;
}
Thank you.
I got array of ints, and I want in order to last element of this array will be shift on top N times, something like this:
int[] array = {1, 2, 3, 4, 5};
And now, last element will be shifted for example 3 times, and it should be expected result:
3, 4, 5, 1, 2
I tried like this:
int[] tab = new int[5];
tab[0] = 1;
tab[1] = 2;
tab[2] = 4;
tab[3] = 5;
tab[4] = 6;
int[] secondTab = new int[5];
int N = 3;
int j = 0;
for (int i=0; i<tab.length-1; i++){
secondTab[i] = tab[(tab.length-1)-N];
N--;
if (secondTab[i+1]==0){
secondTab[i+1] = tab[j];
}
}
It's obviously bad code, j is not getting increment at all so it works only for this example, but I'm wondering what is the best way to do it?
If you want to shift right N times, it means the element at the i-th position will be at the (i+N)%tab.lenth-th position:
for (int i = 0; i < tab.length; i++) {
secondTab[(i+N)%tab.length] = tab[i];
}
If you want to shift the elements in the original array you can try something like this :
int[] array = {1, 2, 3, 4, 5};
int nbShift = 1; // the number of desired shift
for(int i = -1; i < nbShift; i++){
int f = array[0];
for(int j = 0; j < array.length -1 ; j++){
array[j] = array[j + 1];
}
array[array.length - 1] = f;
}
public static void main(String[] args) {
final int[] test = { 1, 2, 3, 4 };
shiftNTimes(test, 2);
for (final int i : test) {
System.out.println(i);
}
}
public static void shiftNTimes(int[] array, int numShifts) {
int timesShifted = 0;
while (timesShifted < numShifts) {
final int temp = array[0];
for (int i = 0; i < (array.length - 1); i++) {
array[i] = array[i + 1];
}
array[array.length - 1] = temp;
timesShifted++;
}
}
For details
I need to write a program which for a given array of ints prints all its elements, but each value only once, without repetitions. That is my tutor said. I agree that there are several example here, but I have special conditions like:
Do not create any auxiliary arrays, collections or Strings!
Do not use any classes from packages other than the standard java.lang.
I have been studying Java not so long so here is what I've done:
public class Third {
public static void main(String[] args) {
int[] p = {5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9};
remove(p);
}
static public void remove(int[] a) {
int min = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
a[i] = min;
}
}
}
for (int j = 0; j < a.length; j++) {
if (a[j] != min) {
System.out.println( a[j] );
}
}
}
}
I realize that this is not efficient, because it is not able to print int's min value. So is there any other way to do it correctly ?
Since you said that you want to print the elements of the array only once, but you cannot use any structures or other arrays to achieve that, I believe your best strategy is to simply scan the array and look for elements with the same value from the index forward, and only print if you haven't found any.
For example: for the array {5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9}, when you look at the first 5, you'll see three more fives to your right so you won't print anything, but when you look at that fourth 5, there'll be non and so you'll print it. When you see -1, for example, you won't see any other -1 to your right, and you'll print it.
public static void main(String[] args) {
int[] p = {5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9};
remove(p);
}
static public void remove(int[] a) {
for (int i = 0; i < a.length; i++) {
boolean found = false;
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
found = true;
break;
}
}
if (!found)
System.out.println(a[i]);
}
}
And the output for your array will be:
-1
2
5
44
12
9
Every element is only printed once
Based on your question here i am providing solution. In this first i am sorting array in ascending order then i am printing current index a[i] if it is not equal to next index a[i+1] .
program:
int a[] = { 5, 2, 2, 5, -1, 5, 12, 2, 5, 44, 12, 9};
int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++)
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
for (int i = 0; i < a.length - 1; i++) {
if (a[i] != a[i + 1]) {
System.out.println(a[i]);
}
if (i == a.length - 2)
System.out.println(a[i + 1]);
}
output:
-1
2
5
9
12
44
Hope it will help you.