I'm very new to java and have been playing around with sorting algorithms. I have the following code working for a set array. I was just wondering what I'd need to change to get it to sort arrays of randoms lengths and integers. I guess the answer is pretty obvious any help is appreciated!
public static void main(String[] args) {
int number[]={8,5,3,2,9};
int temp;
boolean fixed=false;
while(fixed==false){
fixed=true;
for(int i=0; i<number.length-1 ; i++){
if(number[i] > number[i+1]){
temp = number[i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for(int i=0; i<number.length; i++)
System.out.println(number[i]);
}
}
I mean, your algorithm would work regardless of the array's length. About how to generate such arrays, you could do this:
int n = Math.random()*10000 + 1; //so its never 0.
int number[] = new int[n];
for(int i=0;i<n;i++) number[i]=Math.random()*10000;
Everything else stays the same :).
EDIT: You commented on the question that you'd rather generate the array by taking an input from the keyboard. You can do that by using a scanner.
Scanner scanIn = new Scanner(System.in);
do{
int n = scanIn.nextInt();
} while (n<1);
int number[] = new int[n];
for(int i=0;i<n;i++) number[i] = scanIn.nextInt();
scanIn.close();
What you are looking for is probably a method to extract your bubblesort to. Please note that this method changes the input array and does not return a new array.
private static void bubblesort(int[] array) {
int temp;
boolean fixed = false;
while (!fixed) {
fixed = true;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
fixed = false;
}
}
}
}
You can then call it using different approaches.
Fixed size array:
// fixed size array
int number[] = {8, 5, 3, 2, 9};
bubblesort(number);
System.out.println(Arrays.toString(number));
Read numbers from System.in.
// read from sys.in like "2 6 4"
Scanner s = new Scanner(System.in);
String line = s.nextLine();
int[] parsedInts = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
bubblesort(parsedInts);
System.out.println(Arrays.toString(parsedInts));
You can the use Scanner Class in java and need to import java.util.Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array length :");
int n = sc.nextInt();
int number[] = new int[n];
System.out.println("Enter the numbers :");
for(int i = 0; i < number.length; i++) {
number[i] = sc.nextInt();
}
Related
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 2 years ago.
static int[] fun1(int[] ar){
int[] auxarray = new int[ar.length];
int j = ar.length;
for (int i = 0; i < ar.length; i++) {
auxarray[j - 1] = ar[i];
j = j - 1;
}
return ar;
}
I have tried to implement a swap method to modify the same array, but it didn't work (tested with a void method and printed the result inside it: same as the initial array)
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Please enter the size of the array: ");
size = input.nextInt();
array = new int[size]; //array and size are declared private static globally
for(int i = 0; i<size; i++){
array[i] = input.nextInt();
}
System.out.println("Your reversed string is:");
int[] reversedarray = fun1(array);
for(int i = 0; i < size; i++){
System.out.print(reversedarray[i] + ' ');
}
}
This returns 3334353637.. in all cases. Any solution or any idea on what I have done wrong?
error is in your fun1
You are returning a wrong array
What you can consider as an enhancement
You can simply swap the elements in the same array only iterate half the length of the array
static int[] fun1(int[] ar){
int size = ar.length, temp;
for (int i = 0; i < size/2; i++) {
temp = ar[i];
ar[i] = ar[size-1-i];
ar[size-1-i] = temp;
}
return ar;
}
You are returning the wrong array,ar instead of auxarray
Return auxarray instead of ar.
I have an assignment that requires that I create two arrays (with user defined length) full of random numbers between 1-100, then merge the two arrays without duplicates in alternating order. I just need help merging the two without any repeating numbers. Can anyone help? Thanks!
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int f=0;
int j=0;
int k=0;
//getting first array length and making array1 and array2 that length
while (f==0){
System.out.println("Enter an array length (must be 10 or greater):");
int length = scan.nextInt();
if (length < 10){
f=0;
}
else{
f=1;
}
if (f==1){
int [] array1 = new int[length];
int [] array2 = new int[length];
int [] array3 = new int[length*2];
System.out.print("First Array: ");
//creating random integers between 1 and 100 inclusive to fill array1
for (int i=0; i<=length-1; i++){
int x = (int)(Math.random()*100)+1;
array1[i] = x;
System.out.print(x+" ");
}
//creating random integers between 1 and 100 inclusive to fill array2
System.out.print("\nSecond Array: ");
for (int i=0; i<=length-1; i++){
int y = (int)(Math.random()*100)+1;
System.out.print(y+" ");
array2[i] = y;
}
//combining both arrays
System.out.print("\nMerged Array: ");
for (int i=0; i<=length*2-1; i++){
if ((i==0) || (i%2==0)){
array3[i] = array1[j];
j++;
}
else{
array3[i] = array2[k];
k++;
}
System.out.print(array3[i]+" ");
}
}
}
}
}
First, let's extract your method to fill arrays.
static int[] fillRandomArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = (int) (Math.random() * 100) + 1;
System.out.print(arr[i] + " ");
}
System.out.println();
return arr;
}
Now you can simplify your code to use that method, and your merge is very close; you don't need j or k in each case you are indexing by half of i (the cases being even or odd). Like,
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an array length (must be 10 or greater):");
int length = scan.nextInt();
if (length >= 10) {
System.out.print("First Array: ");
// creating random integers between 1 and 100 inclusive to fill array1
int[] array1 = fillRandomArray(length);
// creating random integers between 1 and 100 inclusive to fill array2
System.out.print("\nSecond Array: ");
int[] array2 = fillRandomArray(length);
// combining both arrays
System.out.print("\nMerged Array: ");
int[] array3 = new int[array1.length + array2.length];
for (int i = 0; i < array3.length; i++) {
if (i % 2 == 0) {
array3[i] = array1[i / 2];
} else {
array3[i] = array2[i / 2];
}
System.out.print(array3[i] + " ");
}
System.out.println();
}
}
If you actually need to eliminate duplicates between array1 and array2 while you merge, then you can't assume that the output array will be double the input length. I would use a Set. Like,
// combining both arrays
System.out.print("\nMerged Array: ");
Set<Integer> set = new LinkedHashSet<>();
for (int i = 0; i < array1.length + array2.length; i++) {
if (i % 2 == 0) {
if (set.add(array1[i / 2])) {
System.out.print(array1[i / 2] + " ");
}
} else {
if (set.add(array2[i / 2])) {
System.out.print(array2[i] + " ");
}
}
}
// If you actually need an int[]
int[] array3 = set.stream().mapToInt(Integer::intValue).toArray();
I'm trying to reverse each number in an Integer array using do-while, but I get NullPointerException error.I'm trying to reverse each element in this array: for instance if this is my array:{12,34,56} then the result must be:{21,43,65}.Can someone please help me with this?
public class Reverse {
public int[] revCalculator(int[] number) {
int[] reverse = null;
for (int j = 0; j < number.length; j++) {
do {
reverse[j] = reverse[j] * 10 + number[j] % 10;
number[j] /= 10;
} while (number[j] > 0);
}
return reverse;
}
}
public class ShowReverse {
public static void main(String[] args) {
// instantiation
// -----------------------------------------
Reverse rev = new Reverse();
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter The Number Of Elements: ");
int len = in.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < len; i++) {
System.out.println("Enter Number: ");
numbers[i] = in.nextInt();
}
int[] result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
System.out.print(result);
}
}
pic
You didn't initialize your variable reverseArray, initialize it like so:
UPDATE, I see what you are trying to do, you want to reverse the values of your array, not the array itself
public int[] revCalculator(int[] number) {
int[] reverse = new int[number.length]; //Initialize it to the same size as the passed in arary
//int[] reverse = null; //Problem
StringBuilder sb = new StringBuilder();
for (int j = 0; j < number.length; j++)
{
//You could convert the number to string then reverse it and use parseInt() int
reverse[j] = parseInt(sb.append(number[j].toString()).reverse().toString());
//Clear the StringBuilder object
sb.setLength(0);
}
return reverse;
}
I would recommend initializing the reverse array to an array of the same length as the number array.
int[] reverse = new int[number.length];
There are a couple of changes that you have to make:
initialize reverse array int[] reverse = new int[number.length];
System.out.print(result); would give you the address of result array. You have to show the elements of the array.
int[] result = new int[numbers.length];
result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
//System.out.print(result);
for(int i = 0 ; i<result.length; i++)
System.out.println(result[i]);
Hope this helps.
I'm writing a code that ask at the user to insert the numbers of the array and then write each numbers, do the same thing in another array, and at the end compare the first array with the second array and print out the bubble sort of all numbers, so a kind of bubble sort for the first and second array togheter. I wrote this below, but I don t know how to compare with one method the two different arrays.
public static void main(String[] args) {
public static int[] macello(int[]A){
for(int i=0; i<A.length-1; i++){
for(int j=0; j<A.length-1-i;j++){
if(A[j]>A[j+1]){
int temp = A[j+1];
A[j+1]= A[j];
A[j] = temp;
}
}
}
return A;
}
public static void printArray2(int[]A){
for(int i = 0; i<A.length; i++){
System.out.print(A[i]+",");
}
}
Scanner scan = new Scanner(System.in);
System.out.println("Insert the capacity's array1: ");
int n = scan.nextInt();
int[]numbers1 = {n};
for(int i=0; i<n; i++){
System.out.println("Insert the value of each numbers: ");
int j =0;
numbers1[j] = scan.nextInt();
j++;
}
System.out.println("Insert the capacity's array2: ");
int m = scan.nextInt();
int[]numbers2 = {m};
for(int i=0; i<m; i++){
System.out.println("Insert the value of each numbers: ");
int j=0;
numbers2[j] = scan.nextInt();
j++;
}
macello(Arrays.equals(numbers1,numbers2));
printArray2(Arrays.equals(numbers1,numbers2));
}
}
You mention in the comments that you've already solved bubblesort. So I'm going to assume you have a method with the signature void bubbleSort(int[] arr).
Your code shows you understand how to acquire an array from the user, so we don't need to handle that.
Now what you're describing is bubbleSorting these two arrays. To do this, you need one -big- array that holds them both.
int combinedLength = array1.length + array2.length;
int[] combined = new int[combinedLength];
for(int i = 0; i < array1.length; i++) {
combined[i] = array1[i];
}
for(int i = 0; i < array2.length; i++) {
combined[array1.length + i] = array2[i];
}
// now you can bubbleSort
bubbleSort(combined);
arrayPrint(combined);
Ideally you wrap that logic in a merge method - this particular method leverages the Arrays and System classes to do some of the lifting for you. Obviously you could use the "naive" logic above if you want.
int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
If you also make a method that acquires an array, like this:
public int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
Then your code becomes very, very clean:
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
arrayPrint(c);
I made a driver to test each of these ideas out to make sure they all work. I am a bit concerned, though, because you mention recursion. As you can see in this driver, there is no recursion here. Also be aware that I take a number of shortcuts that are probably not allowed (such as System.arraycopy, Arrays.copyOf, and Arrays.toString). I just wanted to validate the various pieces of functionality. The message uses 1 indexing because that's what most people think in. If you enter 5 elements, they'll be 1-5. You and I know Java stores them 0 indexed, 0-4. It's just a matter of taste and UX.
import java.util.*;
public class BubbleSort {
public static void main(String...args) {
Scanner sc = new Scanner(System.in);
int[] a = acquireArray(sc);
int[] b = acquireArray(sc);
int[] c = merge(a,b);
bubbleSort(c);
printArray(c);
}
public static int[] acquireArray(Scanner sc) {
System.out.println("Length? ");
int len = sc.nextInt();
int[] arr = new int[len];
for(int i = 0; i < len; i++) {
System.out.println("Enter element " + (i+1) + ":");
arr[i] = sc.nextInt();
}
return arr;
}
public static int[] merge(int[] a , int[] b) {
int[] c = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b,0,c,a.length,b.length);
return c;
}
public static void bubbleSort(int[] a) {
boolean swapped = true;
int j = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < a.length - j; i++) {
if(a[i] > a[i+1]) {
int t = a[i];
a[i] = a[i+1];
a[i+1] = t;
swapped = true;
}
}
}
}
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
}
And here's what I get when I run it
C:\files\j>java BubbleSort
Length?
5
Enter element 1:
1
Enter element 2:
5
Enter element 3:
3
Enter element 4:
9
Enter element 5:
7
Length?
5
Enter element 1:
2
Enter element 2:
6
Enter element 3:
4
Enter element 4:
0
Enter element 5:
8
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I am very new to java and I need to create an array that stores numbers and then outputs the numbers in sorted list the mean mode and median.
can anyone tell me if I am on the right track so far with the code below
int number=0;
ArrayList<Integer> listOfNumbers = new ArrayList<>();
Scanner scannerStream = new Scanner (System.in);
System.out.println("Enter list of numbers to Sort: (OR * TO END LIST)");
while(!(listOfNumbers = br.readLine()).equals("*"))
{
listOfNumbers = scannerStream.nextInt();
NumberList = listOfNumbers();
public Vector listOfNumbersSort (int number) {
for (int i=0; i<NumberList; i++) {
int Sort = listOfNumbers();;
return Sort;
// returns the mean
public Vector<Integer> listOfNumbersMean (int number){
return mean;
} // end
// returns the mode
public Vector<Integer> listOfNumbersMode (int number){
return mode;
} // end
// returns the median
public Vector<Integer> listOfNumberMedian (int number){
return median;
} // end
Thanks in advance for any help for advice provided
Use Collections.sort() to sort an ArrayList.
Use Arrays.sort() to sort an array.
can anyone tell me if I am on the right track so far with the code below
Your method definitions does not look good. You are passing a number and expecting the sortedlistofnumbers. Offcourse, if you already have a list, and you sorted it, and then if you get a new number and need to re-sort, then you can have the method signature as you have written, but not at the primary level.
The way you are accepting the list of number is not right. You need a loop. And when you use Arrays, since Arrays are fixed length, you should specify the size too.
see the below code for reference.
If you want to implement sorting in your way, there are various alogorithms like bubble sort.
Sorting Arrays
public class Sorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
int numbers[] = new int[count];
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers[i] = scanner.nextInt();
}
System.out.println("List before sorting..");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
Arrays.sort(numbers);
System.out.println("Sorted list");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
}
}
Sorting ArrayList
public class SorterList {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers.add(scanner.nextInt());
}
System.out.println("List before sorting..");
System.out.println(numbers);
Collections.sort(numbers);
System.out.println("Sorted list");
System.out.println(numbers);
}
}
Edit:
If you want to do custom sorting - say bubble sort algorithm,
int temp;
for (int i = 0; i < (count - 1); i++) {
for (int j = 0; j < count - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) // '> for ascending order'
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}