I still can't get this right. The code in the bubble sort is incorrect. How can I get this right? What should I change or add to get the correct results? Thanks in advance. :)
import java.util.Random;
import java.util.Scanner;
public class HomeWork {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
int e;
Random t = new Random();
for (e = 1; e <= 5; e++) {
System.out.println(t.nextInt(1000));
}
System.out.println(" \n1: BUBBLE SORT ");
System.out.println(" 2: SELECTION SORT ");
System.out.println(" 3: QUICK SORT ");
System.out.println(" Choose a number from 1-3 ");
choice= s.nextInt();
if(choice == 1) {
System.out.print("You chose BUBBLE sort!");
int temp, q, w;
for(int i=0;i<w-1;i++) { //I think there is something wrong here in my bubble sort code.
// What should I add or change to make this correct?
for(int j=0;j<w-1-i;j++) {
if(q[j]>q[j+1]) {
temp = q[j];
q[j] = q[j+1];
q[j+1] = temp;
System.out.println(q[i]+""); // What should I change here to print the correct results?
} else if(choice == 2) {
System.out.print("You chose SELECTION sort!");
} else if(choice == 3) {
System.out.println("You chose QUICK sort!");
} else {
System.out.println("Not in the choices!");
}
}
}
}
}
}
I am still just a beginner. Please please help. Thanks in advance :)
Your problem is that you have not defined q or w--presumably you want them to be the array of numbers and its length. Furthermore, because your bubble sort does not automatically detect when the list has been sorted and stop then, it is more like a combined bubble/selection sort.
public static void main(String[] args) {
int a[] = { 1, 5, 100, 40, 80, 50 };
int length = a.length;
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length - i; j++) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
Like the guy commented above, this the bubble sorting algorithm, and the guy above that, your Variable (w) is wrong, all wrong, and as a tip in the future, post the error, with the code, that's probably why you got a downvote and or because this is pretty simple.
Also forgive me, but i dont have eclipse, and am now coding in C++, but this should work
int x[] = new int[5]
Random t = new Random();
for (e = 1; e <= 5; e++) {
x[e] = t.nextInt(1000); // you didn't even assign any variables to sort, that's one problem, you just printed them.
} // and idk how you get random int's in java, but if this doesn't work, just make your own random int generator.
// There's LOTS of better ones than the one your using now.
int temp, q, w;
for(int i=0;i< 5;i++) {
for(int j=0;j<5-i;j++) {
if(q[j]>q[j+1]) {
temp = q[j-1];
q[j-1] = q[j];
q[j] = temp;
}
// Add 'else ifs' here
}
}
for (int i = 0; i < 5; i++) { // and this will print the results
System.out.print(q[i] + " ");
}
This should work, idk, not really experienced in java >.>, and btw there are tons of books that teach algorithm's, you should first look through your code really well, because of it's a simply mistake like now, these people on stack overflow aren't merciful, there all experience programmer that are really hard on you, but they are smart. (like me :D)
[EDIT] -btw, just merge this with your code, but here are some useful sites.
for random int's - http://www.javapractices.com/topic/TopicAction.do?Id=62
for bubble sort - http://examples.javacodegeeks.com/core-java/bubble-sort-algorithm-in-java-code-example/
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 1, 5, 100, 40, 80, 50 };
int length = a.length;
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length - i; j++) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
Related
Regardless of the programming language you use. You will undoubtedly encounter data while dealing with arrays, particularly duplicates, that you will want to get rid of.
This is my Output
I already inputted the correct syntax of even list array is there something that I missed?
Anyone knows how to remove duplicate element in my even list?
Here's my code:
import java.util.*;
import java.util.Iterator;
public class ArrayBubbleSortwithOddandEven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size, temp;
System.out.print("Size of the list: ");
size = scanner.nextInt();
int number[] = new int[size];
int oddarray[] = new int[size];
int evenarray[] = new int[size];
int odd = 0;
int even = evenarray.length - 1;
for (int i = 0; i < number.length; i++) {
System.out.print("Input: ");
number[i] = scanner.nextInt();
}
for (int i = 0; i < size; i++) {
for (int swap = 1; swap < (size - i); swap++) {
if (number[swap - 1] > number[swap]) {
temp = number[swap - 1];
number[swap - 1] = number[swap];
number[swap] = temp;
}
}
}
for (int i = 0; i < number.length; i++) {
if (number[i] % 2 != 0) {
oddarray[odd++] = number[i];
} else {
evenarray[even--] = number[i];
}
}
for (int i = 0; i < number.length; i++) {
evenarray[even] = evenarray[i];
}
for (int i = 0; i < number.length; i++) {
oddarray[odd] = oddarray[i];
}
for (int i = 0; i < size; i++) { //Bubble sort
for (int swap = 1; swap < (size - i); swap++) {
if (evenarray[swap - 1] > evenarray[swap]) {
temp = evenarray[swap - 1];
evenarray[swap - 1] = evenarray[swap];
evenarray[swap] = temp;
}
}
}
System.out.println("Odd List:"); //Print Odd list
for (odd = 0; odd < oddarray.length; odd++) {
System.out.println("List " + odd + ": " + (oddarray[odd]));
}
System.out.println("Even List:"); //Print Even list
for (even = 0; even < evenarray.length; even++) {
System.out.println("List " + even + ": " + (evenarray[even]));
}
}
}
you can use a Set\HashMap to remember which number you already discover during your iteration. GOOD LUCK !
You can read about Data Structures - just google it :).
here a few questions that might help you understand.
Data Structures for hashMap, List and Set
Why key in HashMap can't be duplicated
how to find duplicate item position from set in java
I've a question to you.
https://stackoverflow.com/questions/14975968/vertical-arrangement-with-asterisk#=
The code which you shared this post is very good. I've an exam tomorrow. May you tell me the solution.
I edited int array in this program.
It's {-1, 2, 5, 3} but program is not printing (-1) value in which int array.
I want to When the loop read this minus value, it cross new line and print "*" and print the minus value to its underline.
Can you tell me how can i do that in Java?
Thank you.
https://i.stack.imgur.com/ESsVE.jpg
public static void main(String[] args) throws IOException {
int[] a = new int[] {-1,3,-4,2,5};
int[] tmp = a.clone();
Arrays.sort(tmp);
int max = tmp[tmp.length-1];
int low = tmp[0];
int last =max;
if(low<0) {
last=max-low;
}
for (int i = 0; i < last+1; i++) {
for (int j = 0; j < a.length; j++) {
if (i == last ) {
System.out.print(a[j]);
} else if(i<max){
if (i < max - a[j])
System.out.print(" ");
else
System.out.print("*");
}
else {
if (i < max - a[j] )
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;
"Your program should proceed as follows:
Display a welcome message.
Prompt the user for an integer which is 3. If the number entered is < 3. keep prompting the user until they enter a number 3 (use a do/while). This number will determine the size of the square array.
Fill the array as per pattern 1 and display it using printf to format the array.
Fill the same array as per pattern 2 and display it using printf t0 format the array.
Display a closing message."
Pattern:
I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?
Also any tips on to how to go about the second patterns.
Here is my code.
import java.util.Scanner;
public class a3q33
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n;
do
{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int [][] arr = new int [n][n];
int i, j, k=1;
for(i=0;i<n;i++)
{
if(i % 2 != 0)
{
for(j=n;j>0;j--)
{
k = k+n;
arr[i][j]=k;
k--;
}
}
else
{
for(j=0;j<n;j++)
{
arr[i][j]=k;
k++;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf(arr[i][j]+" ");
}
System.out.printf("");
System.out.println();
}
}
}
Any help would be greatly appreciated!
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?
Also, the for loop in your code:
for(j=n;j>0;j--)
This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.
Instead, try using:
for(j=n-1;j>-1;j--)
It would be a good first steps to look into.
import java.util.Scanner;
public class a3q33{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int n;
do{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int count = 1;
int [][] arr = new int [n][n];
for(int i = 0;i<n; i++){
if(i%2==0){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
else{
for(int j = n-1;j>=0; j--){
arr [i][j] = count;
count++;
}
}
}
System.out.println("\nPattern 1 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
// reset count back to 1 and fill the array in the same way only without the if/else
// for n = 5 for example this will produce [1, 2, 3, 4, 5 ]
// [6, 7, 8, 9, 10]
// [11,12, 13, 14, 15]
// [16,17, 18, 19, 20]
// [21,22, 23, 24, 25]
count = 1;
for(int i = 0;i<n; i++){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
// rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
//http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
//
for (int i = 1; i<n; i++){
int [] temp = new int [n];
for (int j = 0; j < n; j++) {
temp[(j + i) % n] = arr[i][j];
}
System.arraycopy(temp, 0, arr[i], 0, n);
arr[i]=temp;
}
System.out.println("\nPattern 2 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
}
You can achieve this by checking the modulo:
for (int i = 0; i < n; i++) {
int start = i * n;
for (int j = 0; j < n; j++) {
arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
}
}
currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms.
Here is the challenge:
I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number.
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
public void recursion(ArrayList<Integer> specs){
//number of nested loops will be equal to: specs.size();
//each item in specs, specifies the For loop max count e.g:
//First outside loop will be: for(int i=0; i< specs.get(0); i++)
//Second loop inside will be: for(int i=0; i< specs.get(1); i++)
//...
}
The the results will be similar to outputs of this manual, nested loop:
int[] i;
i = new int[7];
for( i[6]=0; i[6]<5; i[6]++){
for( i[5]=0; i[5]<7; i[5]++){
for(i[4] =0; i[4]<9; i[4]++){
for(i[3] =0; i[3]<2; i[3]++){
for(i[2] =0; i[2]<8; i[2]++){
for(i[1] =0; i[1]<9; i[1]++){
//...
System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]);
}
}
}
}
}
}
I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.
// ...
recursion (specs, specs.size () - 1);
// ...
public void recursion(ArrayList<Integer> specs, int startWith){
for (int i = 0; i < specs.get(startWith); i++) {
// ...
if (startWith - 1 >= 0)
recursion (specs, startWith - 1);
}
}
Your function also need to now the index of the specs array to use for iteration, and also the previous numbers that should be printed:
public void recursion(ArrayList<Integer> specs, int index, String output) {
if( index >= specs.size() ) {
System.out.println(output);
return;
}
for (int i = 0; i < specs.get(index); i++ )
recursion( specs, index+1, Integer.toString(i) + " " + output );
}
The you should call it like this:
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5);
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
recursion( specs, 0, "" );
Does this snippet give the output you want? (It is compileable and executeable)
import java.util.ArrayList;
import java.util.List;
public class SO {
static ArrayList<Integer> specs = new ArrayList<Integer>();
static int[] i;
public static void main(String[] args) throws Exception {
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
i = new int[specs.size()];
printMe(0, specs, i);
}
static void printMe(int depth, List<Integer> _specs, int[] i) {
if (_specs.isEmpty()) {
System.out.println(printI(i));
return;
} else {
for (int j = 0; j < _specs.get(0); j++) {
i[depth] = j + 1; // + 1 since you seems to want to go from 1 and not 0
printMe(depth + 1, _specs.subList(1, _specs.size()), i);
}
}
}
static String printI(int[] i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i.length; j++) {
sb.append(i[j]);
if (j < i.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}
You can try this :
public static void loops(ArrayList<Integer> specs, int idx, StringBuilder res){
if(idx==specs.size()-1){
for (int i = 0; i < specs.get(idx); i++) {
System.out.println(i+" "+res);
}
}
else{
for(int i=0;i<specs.get(idx);i++){
res.insert(0,i+" ");
loops(specs,idx+1,res);
res.delete(0, 2);
}
}
}
And call with :
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
loops(specs,0, new StringBuilder());
I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}