While loop after 1st iteration is not updating array values - java

I am trying to code cyclic sort and following is my code.
public static void main(String[] args) {
int temp = 0;
int[] nums = new int[]{4,2,1,3};
for(int i=0; i<nums.length; i++){
while(nums[i]!=nums[nums[i]-1]){
// line#8
System.out.println(nums[i] + " " + nums[nums[i]-1]);
temp = nums[i];
nums[i] = nums[nums[i]-1];
nums[nums[i]-1] = temp;
}
}
for(int i:nums){
System.out.println(i);
}
}
After 1st iteration in while loop:
i=0, nums[] = {3,2,1,4}. But after 1st iteration in while loop, if nums[0]=3, then nums[nums[0]-1] = 1, which is not the case i.e. nums[nums[0]-1] = 4. Also, this code will run into infinite loop and elements 3 & 4 will keep swapping.
Could someone explain me why while loop is not interpreting nums[nums[0]-1] as 1?
TIA

I revised your code it will work. you should store nums[i] - 1 value before you change nums[i].
int temp = 0;
int[] nums = new int[]{4, 2, 1, 3, 6, 8, 5, 7};
for (int i = 0; i < nums.length; i++) {
while (nums[i] != nums[nums[i] - 1]) {
temp = nums[i];
int index = nums[i] - 1;
nums[i] = nums[nums[i] - 1];
nums[index] = temp;
}
}
for (int i : nums) {
System.out.println(i);
}

Related

DeleteZero's using Java

I need to finish this code which involves deleting all the zero's stored in the array. I thought it was complete but it won't compile, it's my last line that is dubios and I'm not getting right. Thank you.
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
for (int i = 0; i < 20; i++) {
rand[i] = (int)(Math.random());
}
System.out.println(array(a));
}
}
Few errors.
This would always insert 0 at rand[i] because you are casting Math.random() to int which will always become zero.
rand[i] = (int)(Math.random());
Change it to sth like this. I have written 10 but you can write any number to define the range.
rand[i] = (int)(Math.random()*10);
This line is also wrong:
System.out.println(array(a));
You need to print the array by looping over it, but more importantly your function array() returns a new array, which should be stored somewhere before printing it.
Here is a possible workaround
rand = array(rand);
for (int i=0; i<rand.length; i++){
System.out.println(rand[i]);
}
The compile time error is due to the fact that, in the main method you have created the array named rand and passing the array named a. from the main method call System.out.print(array(rand))
You can try Java 8's Stream, which turns the whole logic to one line return Arrays.stream(a).filter(n -> n!= 0).toArray();
Little fixed your code:
import java.util.Random; // Import Random
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
} else {
System.out.println("Skip at position: [" + i + "] because a[i] == "+a[i]+";"); // Display what removed.
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
Random rnd = new Random();
for (int i = 0; i < 20; i++) {
rand[i] = rnd.nextInt(11) + 0; // 11-1 = max, 0 = min
}
int[] a = array(rand);
System.out.println(a); // since it prints something like this: [I#106d69c, we should print all elements manually through a loop.
System.out.println("a.length = " + a.length + ", rand length: " + rand.length);
System.out.print("[");
for (int i = 0; i != a.length; i++) {
String space = ", ";
if (i == a.length-1) //if last not print space
space = "";
System.out.print(a[i]+space); // Print all elements
}
System.out.print("]\n");
}
}
Example of output:
Skip at position: [2] because a[i] == 0;
Skip at position: [8] because a[i] == 0;
Skip at position: [10] because a[i] == 0;
Skip at position: [12] because a[i] == 0;
Skip at position: [16] because a[i] == 0;
[I#106d69c
a.length = 15, rand length: 20
[6, 8, 1, 8, 7, 1, 3, 5, 3, 8, 5, 2, 7, 2, 8]

Java Selection Sort

I am having issues getting my sort to check every index. It skips the 3rd indices for j as in it goes i[0], j[2], to i[0], j[4] I don't know why it is doing that?. Also, I am having trouble with my numbers actually be swapped. Does anybody know where my error is?
static void selectionSort(int[] arr) {
final long startTime = System.nanoTime(); // starts timer
System.out.println("Selection Sort");
//************** Code For Sorting *****************//
//*************************************************//
int counter = 0;
int first = 0;
int second = 0;
// Copies unsorted array to new array
//int[] sorted = Arrays.copyOf(arr, arr.length);
// sorts unsorted array for comparison later on
//Arrays.sort(sorted);
// comparing the first index value to
// the rest of the values in the array
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
// representing the next index value
// to the original and comparing it
for (int j = 1; j < arr.length - 1; j++) {
int nextIndex = j;
if (arr[minIndex] < arr[nextIndex]) {
System.out.println("i: " + i);
System.out.println("j: " + j);
System.out.println("Checking next index");
}
if (arr[minIndex] > arr[nextIndex]) {
System.out.println("i: " + i);
System.out.println("j: " + j);
//counter = j; // getting array index
first = arr[minIndex];
second = arr[nextIndex];
minIndex = second;
arr[minIndex] = second;
System.out.println("first:" + first);
System.out.println("second:" + second);
System.out.println("minIndex:" + minIndex);
System.out.println("arr[minIndex]:" + arr[minIndex]);
System.out.println("Possible lowest unsorted value");
}
//Swap here
if (arr[arr.length - 1] == arr[j]) {
arr[0] = second;
arr[counter] = first;
counter = 0;
//minIndex= i+1;
}
}
for (int k = 0; k < arr.length; k++) {
System.out.print(arr[k] + ", ");
}
System.out.println();
}
}
The first mistake you've made is within your nested for loop. the starting index (j) for the inner loop should always start at i + 1 (one place ahead of the indexer i) for each iteration of the outer for loop not j = 1 as you've done.
Second, by having the condition j < arr.length-1 you'll always exclude the last element within the array.
change this:
for(int j = 1; j < arr.length-1; j++)
to this:
for(int j = i + 1; j < arr.length; j++)
Moving on, there seems to be several problems with your algorithm including your swap functionality so, let's start again.
Selection sort is an in-place comparison-based algorithm in which the array is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire array.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.
with that in mind, now we can start the algorithm.
public static void selectionSort(int[] arr){
for(int i = 0; i < arr.length-1; i++){
int minIndex = i; // smallest element index
for(int j = i + 1; j < arr.length; j++){
if(arr[j] < arr[i]){ // find smallest element
if(arr[j] < arr[minIndex])
minIndex = j; // update smallest element index
}
}
if(i != minIndex){ // swap
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// print the result
Arrays.stream(arr).forEach(System.out::println);
}
as a side note, Selection sort complexities are of Ο(N2), where N is the number of elements within the array.
The algorithm of the selection sort looks as follows:
public static void selectionSort(int[] arr) {
// iterate over all subsets of the array
// (0-last, 1-last, 2-last, 3-last, ...)
for (int i = 0; i < arr.length; i++) {
// assume the min is
// the first element
int min = arr[i];
// index of the
// min element
int min_i = i;
// check the elements
// after i to find
// the smallest
for (int j = i + 1; j < arr.length; j++) {
// if this element
// is less, then it
// is the new min
if (arr[j] < min) {
min = arr[j];
min_i = j;
}
}
// if min element is not
// equal to the current
// one, then swap them
if (i != min_i) {
int temp = arr[i];
arr[i] = arr[min_i];
arr[min_i] = temp;
}
}
}
public static void main(String[] args) {
int[] arr = {5, 34, 1, 15, 3, 8, 9, 2, 7, 6, 43, 4};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 34, 43]
}

How to shift N times last element of the list on top

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

Given an array with odd length, look at the first, last, and middle values in the array and return an array with those three values

So for any given odd length array, I need to look at the first, middle and last value, and return an array with only hose 3 values but in ascending order.This is what I have, but it's only working with arrays of 3 elements, it's not working for other odd length arrays:
public int[] maxTriple(int[] nums) {
int toSwap, indexOfSmallest = 0;
int i, j, smallest;
for( i = 0; i < nums.length; i ++ )
{
smallest = Integer.MAX_VALUE;
for( j = i; j < nums.length; j ++ )
{
if( nums[ j ] < smallest )
{
smallest = nums[ j ];
indexOfSmallest = j;
}
}
toSwap = nums[ i ];
nums[ i ] = smallest;
nums[ indexOfSmallest ] = toSwap;
}
return nums;
}
You're getting the sorted array, so if you need just the first, middle and last values you can try it like this:
public int[] maxTriple(int[] nums) {
int toSwap, indexOfSmallest = 0;
int i, j, smallest;
for( i = 0; i < nums.length; i ++ )
{
smallest = Integer.MAX_VALUE;
for( j = i; j < nums.length; j ++ )
{
if( nums[ j ] < smallest )
{
smallest = nums[ j ];
indexOfSmallest = j;
}
}
toSwap = nums[ i ];
nums[ i ] = smallest;
nums[ indexOfSmallest ] = toSwap;
}
nums=new int[]{nums[0],nums[(nums.length/2)],nums[nums.length-1]};
return nums;
}
You're thinking about this too hard. If the length of your array is less than 3 or even, return null.
Otherwise, get the first element, the last element, and the middle element and store them in a new array. Sort the array with Arrays.sort() and return the new array.
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4})));
System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4, 5})));
System.out.println(Arrays.toString(maxTriple(new int[] {75, 99, 4, 999, 4, 65, 23})));
}
public static int[] maxTriple(int[] nums) {
if (nums.length < 3 || nums.length % 2 == 0) {
return null;
}
int[] result = new int[3];
result[0] = nums[0]; // First
result[1] = nums[nums.length - 1]; // Last
result[2] = nums[nums.length / 2]; // Middle
Arrays.sort(result);
return result;
}
Results:
null
[1, 2, 5]
[23, 75, 999]
I used another approach with ternary operators. I hope it can be useful...
public int maxTriple(int[] nums) {
return (nums[0] > nums[nums.length/2]) ? (nums[0] > nums[nums.length-1] ?
nums[0] : nums[nums.length-1]) : (nums[nums.length/2] > nums[nums.length-1]
? nums[nums.length/2] : nums[nums.length-1]);
}
This code works fine:
public int[] maxTriple(int[] nums) {
int[] myArray = new int[3];
int length = nums.length;
int middle = nums[(length + 1) / 2 - 1];
int last = nums[length - 1];
int first = nums[0];
myArray[0] = nums[0];
myArray[1] = nums[middle];
myArray[2] = nums[last];
return myArray;
}
What you are tyring to do is called selection sort. Here is the code for that:
int[] maxTriple(int[] nums, int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = i; j < size; j++) {
if (nums[j] < nums[i]) {
int toSwap = nums[i];
nums[i] = nums[j];
nums[j] = toSwap;
}
}
}
return nums;
}

Problems in ArrayList<Integer>

import java.util.*;
import java.util.Random;
class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
int dupe = 0;
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
//remove second num if two numbers akike
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n-dupe;
dupe = 0;
}
System.out.println("Duplicates: " + (20 - arr.size()));
for (int n3 = arr.size(); n3 < 20; ++n3) {
int randomnumbers = generate.nextInt(50);
arr.add(randomnumbers);
//check for duplicates again
for (int n = 0; n < arr.size(); n++) {
Integer check1 = arr.get(n);
for (int n2 = n+1; n2 < arr.size(); n2++) {
Integer check2 = arr.get(n2);
if (check1.equals(check2)) {
arr.remove(check2);
n2 = n2-1;
dupe = 1;
}
}
n = n - dupe;
dupe = 0;
}
}
//before sort
System.out.println(arr);
System.out.println("");
for(int a=0; a<20; a++){
for (int b = 0; b < 19; b++) {
if(arr[b] > arr[b+1]){
int temporary = arr[b];
arr[b] = arr[b+1];
arr[b+1] = temporary;
}
}
}
System.out.println("\nSorted Array:\n");
for (int a = 0; a < 20; a++) {
System.out.println("Array [" + a + "]: " + arr[a]);
}
}
}
Can anyone tell me what I did wrong for this one, I can't seem to generate the last part. Shouldn't the ArrayList arr = new ArrayList(); run same with the last part where arr[b] is work? I'm new to Java so would greatly appreciate if simple explaination/metaphor is ued provided with solution.
P.S: I'm not planning to use a library sort function like Collection, I'm required to use the sorting method at the last part.
arr[a] is the syntax to access array elements. For ArrayLists you use arr.get(a). And to assign a value to an ArrayList, you use arr.set(b,value). You can't use the assignment operator.
The problem you are having is that you are trying to remove your duplicates before sorting. First, sort your integers, duplicates and all, and then remove the duplicates.
import java.util.ArrayList;
import java.util.Random;
public class ArraySorting {
public static void main(String[]args) {
ArrayList<Integer> arr = new ArrayList<Integer>();
Random generate = new Random();
for (int nums = 0; nums < 20; nums++) {
int randomnumbers = generate.nextInt(10);
arr.add(randomnumbers);
}
System.out.println("First list of 20 generated numbers: ");
System.out.println(arr);
System.out.println("");
// SORT YOUR LIST FIRST
bubbleSort(arr);
System.out.println(arr);
// NOW YOU CAN REMOVE YOUR DUPLICATES
removeDuplicates(arr);
System.out.println(arr);
}
public static void bubbleSort(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
for(int j = 1; j < (list.size() -i); j++) {
if(list.get(j - 1) > list.get(j)) {
int temp = list.get(j-1);
list.set(j-1, list.get(j));
list.set(j, temp);
}
}
}
}
public static void removeDuplicates(ArrayList<Integer> list){
for(int i = 0; i < list.size(); i++) {
if(i < list.size()-1) {
int prev = list.get(i);
int curr = list.get(i + 1);
if(curr == prev) {
list.remove(list.get(i + 1));
i--;
}
}
}
}
}
Output
First list of 20 generated numbers:
[9, 2, 2, 1, 3, 4, 0, 9, 5, 2, 5, 7, 4, 9, 0, 4, 0, 6, 6, 6]
[0, 0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7, 9, 9, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 9]

Categories