I have been confronting with a very confusing situation, I wrote this BubbleSort program and it ran just fine. with the correct output:
public class BubbleSortInput {
private static void Sorting(int[] intArray)
{
int i, temp=0;
int n = intArray.length;
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
}
public static void main(String[] args) {
int array[] = {1,5,65,34,76,234};
Sorting(array);
for(int k = 0; k < array.length; k++)
{
System.out.println(array[k]);
}
}
}
However, I tried to write basically the same code, in the main method, in another class:
class BubbleSort {
public static void main(String[] args) {
int numbers[] = {12,43,65,12,65,92,32,54};
int i,temp=0;
for(i=0; i < numbers.length-1; i++)
{
for(int j = 0; j < numbers.length-i-1; j++)
{
if(numbers[i]>numbers[i+1])
{
temp = numbers[i+1];
numbers[i] = numbers[i+1];
numbers[i]= temp;
}
}
}
for(i=0;i<numbers.length;i++)
{
System.out.println(numbers[i]);
}
}
}
The output I get on the second file is completely wrong, even though I used almost the same code, Can someone explain this please?
Output:
12
43
12
12
65
32
32
54
As others pointed out, you should take a look at the bubble sorting algorithm. And just a reminder, run many test cases before stating that your original piece of code works fine. Just to be clear, the first program also gives a wrong output. The output you may have gotten for your input set may be true, but that was a bit sorted to begin with. Try the input set you used in the second program for your first code and identify the errors.And also, take a look at the swapping code inside your for loops.
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
You are assigning the value at [i+1] position to temp. And you are again assigning the value at [i+1] to the location i. So the value at the location [i] was lost in the process. Now value at location [i] and [i+1] are same. So work on that as well.
That aside. In Bubble sort, sorting works by swapping adjacent elements. So by the end of the first pass(ascending order sorting), the largest element in the array will be at the end. This process goes on until, all the elements are sorted.
Example:
First Pass:
( 6 1 3 2 9 ) –> ( 1 6 3 2 9 ), Here, algorithm compares the first two elements, and swaps since 6 > 1.
( 1 6 3 2 9 ) –> ( 1 3 6 2 9 ), Swap since 6 > 3
( 1 3 6 2 9 ) –> ( 1 3 2 6 9 ), Swap since 6 > 2
( 1 3 2 6 9 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (9 > 6), algorithm does not swap them.
Second Pass:
( 1 3 2 6 9 ) –> ( 1 3 2 6 9 )
( 1 3 2 6 9 ) –> ( 1 3 4 6 9 ), Swap since 3 > 2
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9) –> (1 2 3 5 9 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 3 5 9 ) –> (1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
( 1 2 3 5 9 ) –> ( 1 2 3 5 9 )
I don't think your bubble sorting code is correct. Here is your loop:
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < n-i-1; j++)
{
if(intArray[i]>intArray[i+1])
{
temp = intArray[i+1];
intArray[i] = intArray[i+1];
intArray[i] = temp;
}
}
}
Note that you never use the variable j. So all it does is loop through the array and then swap the two elements if the first one is larger than the second one. You should take a look at the Bubble sort algorithm again and re-write your code.
The sorting logic you are using is incorrect.
Bubble sort compares each pair of adjacent items and swaps them if they are in the wrong order (not in ascending order).
By the end of the first pass(ascending order sorting), the largest element in the array will be at the last index.
By the end of the second pass(ascending order sorting), the second largest element in the array will be at the second last index and so on.....
Visit http://visualgo.net/sorting for better understanding.
So, in your code you should compare the items with the 2nd initialization (variable j in your case). After modification it should look like:
for(i=0; i < n - 1; i++)
{
for(int j = 0; j < (n-i)-1; j++)
{
if(intArray[j]>intArray[j+1])
{
temp = intArray[j];
intArray[j] = intArray[j+1];
intArray[j+1] = temp;
}
}
}
Related
From GeeksforGeeks I found this defination :
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
What if I do this in reverse order like from n-1 to 0? Is it right because I am putting my array's smallest bubble into the first position on the first pass.
I have written my code like this:
for (int i = 0; i < array.length; i++) {
for (int j = array.length - 1; j > 0; j--) {
if (array[j - 1] > array[j]) {
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
Yes, your code will work.
But in order to increase the efficiency of your program in terms of speed, you should change the condition in the second for loop. As you have written
for (int j = array.length - 1; j > 0; j--) {
...
}
Here, in the Second Pass, when the value of j is 1 then, it will unnecessarily check this condition
array[j - 1] > array[j]
Because, After the first pass, array[0] is already the smallest. So, you don't need to check that again.
And in the third pass, there will be two unnecessary conditions and so on and so on.
Therefore, I recommend you to use j > i as the condition of second for Loop. Then your whole line will be
for (int j = array.length - 1; j > i; j--) {
...
}
The idea is finally to sort the list.
Below is the Python code for filling the lowest number first and then going to the highest number
def selection_sort(input_list):
for init in range(0,len(input_list)):
pos_of_min=init
for nxt in range(pos_of_min+1,len(input_list)):
if input_list[pos_of_min]>input_list[nxt]:
pos_of_min=nxt
input_list[init]=input_list[pos_of_min]
input_list[pos_of_min]=input_list[init]
return input_list
arr_unsorted=[25,67,23,21,90,89,45,63]
sorted_result=selection_sort(arr_unsorted)
print(sorted_result)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
please explain the j+1
In sorting program i saw this line.please explain
code is here
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j + 1])
{
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = tempVar;
}
}
}
This code goes through an array and checks if the number at array[i] is greater than the number at array[i + 1] meaning number number to the right of array[i]. Then it swaps them. This is a sorting algorithm called Bubble sort. So if there is an array ( 3 2 1 ) the loop would go through, see that 3 > 2, swap 3 and 2 then see that 2 > 1 and swap 2 and 1. The array isn't fully sorted yet, but with enough passes it will be. That is the idea behind Bubble sort
Step by step example:
Lets say we have an array ( 5 1 4 2 8 ) and we want to use bubble sort to sort it.
First Pass:
( 5 1 4 2 8 ) to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) to ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) to ( 1 4 2 5 8 ), Already in order -> no swap
( 1 4 2 5 8 ) to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) to ( 1 2 4 5 8 ), Already in order -> no swap
( 1 2 4 5 8 ) to ( 1 2 4 5 8 ), Already in order -> no swap
Now, the array is already sorted, but our algorithm does not know if it is
completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) to ( 1 2 4 5 8 ), Already in order -> no swap
( 1 2 4 5 8 ) to ( 1 2 4 5 8 ), Already in order -> no swap
( 1 2 4 5 8 ) to ( 1 2 4 5 8 ), Already in order -> no swap
( 1 2 4 5 8 ) to ( 1 2 4 5 8 ), Already in order -> no swap
Now we see that no swaps have been made and this means that the array is completely sorted
for (int i = 0; i < numbers.length; i++)
our first index, allows us to have a starting point for each iteration
{
for(int j = i+1; j < numbers.length; j++)
our second index, allows us to not make redundant swaps and runs the faster without error
{
if(numbers[i] > numbers[j])
is i greater than j? if yes
{
tempVar = numbers [j];
set tempVar to have the same value as the element of numbers at j
numbers [j]= numbers [i];
swaps the values, tempVar stored the backup prior to this statement. The element of numbers at j is overwritten
numbers [i] = tempVar;
swaps the values, tempVar is used to overwrite the element of numbers at i
}
}
}
Use this resource to boost your knowledge: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html
As I said, I would like to "scroll" through a Multi Dimensional array via the secondary diagonal, my desired input to be: (Case a) [It can be in either C++ or Java, it doesn't matter]
NOTE+EDIT: The order is not random. It starts from the 1 at the bottom and goes its way up.
Is this possible?
If not then at least half of the code? (Case b)
// Case a:
16 15 13 10
14 12 9 6
11 8 5 3
7 4 2 1
// Case b:
0 0 0 1
0 0 9 6
0 8 5 3
7 4 2 1
You can do this with a simple loop (this is Java):
int size = 4;
int[][] matrix = new int[size][size];
// . . .
for (int i = 0; i < size; ++i) {
doSomethingWith(matrix[i][size - i - 1]);
}
int[][] a={{7,6,4,1},{5,3,9,6},{2,8,5,3},{7,4,2,1}};
for(int i=0; i<a.length; i++)
{
for(int j=a[i].length-1; j>=a[i].length-(i+1); j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
I am trying to create a nested for loops that will generate all the pairs in a range specified by the user, ranging from negative values to positive values. It is a little tough to explain, but here is the code I have:
public class test method {
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = 3;
int d = 4;
for (int i = -a; i <= a; i++)
for (int j = -b; j <= b; j++) {
System.out.println(a+" and "+b+" vs "+c+" and "+d+"\n");
}
}
}
Given command line arguments 1 and 2, my desired output would be something like:
-1 and -2 vs 3 and 4
-1 and -1 vs 3 and 4
-1 and 0 vs 3 and 4
-1 and 1 vs 3 and 4
-1 and 2 vs 3 and 4
0 and -2 vs 3 and 4
0 and -1 vs 3 and 4
0 and 0 vs 3 and 4
0 and 1 vs 3 and 4
0 and 2 vs 3 and 4
1 and -2 vs 3 and 4
1 and -1 vs 3 and 4
1 and 0 vs 3 and 4
1 and 1 vs 3 and 4
1 and 2 vs 3 and 4
I assume the lack of brackets in the first for is a problem in the copy & paste, but if that's your real code you've got a problem there.
a = Math.abs(a);
b = Math.abs(b);
for (int i = -a; i <= a; i++) {
for (int j = -b; j <= b; j++) {
System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");
}
}
Two things. First of all you should be printing i and j and second you should also consider negative values. Your for's will fail since -a if a = -1 will result in
for (int i = 1; i <= -1; i++)
The condition will not be met and the iteration won't take place. By doing Math.abs you get the absolute value of the inputs and you can do the iteration from that negative value to the positive one. If both a and b are positive the abs method will return the same values (assigning a and b with the same values they already have).
Whatever should be done with c and d remains to be seen. Your desired output says you leave them as they are so I won't touch them by now.
looks reasonable, exception for the '-a' business (and printing the wrong variables)
Assuming a/b are always positive, try
for (int i = (0-a); i <= a; i++)
for (int j = (0-b); j <= b; j++) {
System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");
For example, say we have a Sudoku board like this:
0 0 6 5 8 9 7 4 3
0 5 0 0 0 0 0 6 0
7 0 9 0 6 0 1 0 0
0 3 0 0 0 2 0 8 7
0 0 1 0 0 0 4 0 0
8 9 0 6 0 0 0 5 0
0 0 2 0 5 0 3 0 6
0 7 0 0 0 0 0 9 0
3 1 8 4 9 6 5 0 0
I want to store it into one array such that the first 9 elements of the array are the first sub block, i.e. the values {0 0 6 0 5 0 7 0 9} and followed by {5 8 9 0 0 0 0 6 0}.
I've tried finding a solution but I always get an array index out of bounds error and it is too brute force. Something similar to this:
while(st.hasMoreTokens()) {
if(ctr == 27) {
c.addSubBlock(sb1);
c.addSubBlock(sb2);
c.addSubBlock(sb3);
sb1 = new SubBlock();
sb2 = new SubBlock();
sb3 = new SubBlock();
ctr = 0;
}
sb1.addElement(Integer.parseInt(st.nextToken()));
sb1.addElement(Integer.parseInt(st.nextToken()));
sb1.addElement(Integer.parseInt(st.nextToken()));
sb2.addElement(Integer.parseInt(st.nextToken()));
sb2.addElement(Integer.parseInt(st.nextToken()));
sb2.addElement(Integer.parseInt(st.nextToken()));
sb3.addElement(Integer.parseInt(st.nextToken()));
sb3.addElement(Integer.parseInt(st.nextToken()));
sb3.addElement(Integer.parseInt(st.nextToken()));
ctr+=9;
}
Please give me some tips. Code snippets would also be a great help.
EDIT: This thread somehow helped me figured it out. And yes, this is part of the Sudoku where I'm trying to encode the board into an array.
What I did was to transform first the input String into a 2d array (9x9) and use int block = (row/3)*3 + (col/3); to compute exactly which sub block each element belongs.
Create a 3x3 array of sub blocks
Use 2 counters (x & y) for tracking the position in the full board of each element read
Add the values at (x,y) into sub block (x/3,y/3)
Something like this:
SubBlock board[][] = new SubBlock[3][3];
int x, y;
for ( y=0; y<9; y++ )
for ( x=0; x<9; x++ )
board[y/3][x/3].addElement(Integer.parseInt(st.nextToken()));
board[0][0] will be the top-left SubBlock, board[2][2] the bottom-right one.
Store everything in a two dimension array. E.g.
int[] board = {
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}
{1,2,3,4,5,6,7,8,9}};
//looping
public static void Main(string[] args){
for(int i = 0; i < 9; i++)
{
System.out.println("SubBlock number"+i);
for(int j = 0; j < 9; j++){
System.out.println(board[i][j]);
}
}
}
Assuming that you are reading input left to right, top to bottom, try a set of 4 nested loops like this:
int board[] = new int[81];
for (int outY = 0; outY < 3; outY++)
{
for (int outX = 0; outX < 3; outX++)
{
for (int inY = 0; inY < 3; inY++)
{
for (int inX = 0; inX < 3; inX++)
{
board[27*outY + 9*outX + 3 * inY + inX] = //parse an int from your input here
}
}
}
}
It would be great if we knew why you are trying to loop through the board.
If you want to check if you can enter a number, I recommend you use maps for each of the 3x3 squares.
Then check if the item is in the map already or not. For the rows and columns, you can either loop over the 2D array and check each element, or -again- use a map for each column and a map for each row.
I'm not entirely sure if you want an answer for a single-dimension array or if you're willing to make it a two-dimensional array (as you mention each nine element set with curly braces), but if two-dimensional is OK...
The OP in this Code Review posting used a 'fancy' way of sifting through the subgrids by using the math (i % 3) + rowStart inside one of the square brackets and (i / 3) + colStart inside the other. One commenter noted this modulo method to be a bit obscure, and I'm prone to agree, but for how clean it is and the fact that it works, I think it's a solid solution. So, paired with the iteration of the for loop, we can sift through each 'subgrid' cell, as well as each element of row + col.
for(i=0; i<9; ++i)
{
if (puzzle[row][i] == num) return 0;
if (puzzle[i][col] == num) return 0;
if (puzzle[rowStart + (i%3)][colStart + (i/3)] == num) return 0;
}
If we find a number in one of the cells that matches, it's a duplicate, and we exit the function as 'false', or, 0.
EDIT:
Now that I think of it, you could use this same trick for a single-dimension array by using i % 9 instead of 3. You could then determine which 'row' we're on by doing i / 9 and trusting that, since we're dealing with type ints, we'll truncate the unnecessary decimals.
This does verify that this trick is a bit prone towards N-1 indexed data, as someone would assume 'go to the 81st element' would mean go to the 9th column of the 9th row, but using 81 % 9 would yield 0, and 81 / 9 would yield 9, so we'd go to the 0th place at row 9.