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
Related
i want devide matrix into four sub-blocks equally by vertically and horizontallty in java (Here, we suppose that m and nare even numbers) .
for example we have matrix:
1 2 3 4 5 6
7 8 9 1 2 8
1 2 3 4 5 6
4 5 6 7 8 9
1 4 7 2 5 8
3 6 9 7 2 5
I want to display the last block that is:
7 8 9
2 5 8
7 2 5
how i can resolve this problem in java.
Iterate over the lower-right part of the matrix. Here is an example for a square matrix. I am sure you will be able to make it more generic for non-square quadrants or to get other quadrants than the lower-right one.
public int[][] getQuadrantOfSquareMatrix(int[][] matrix) {
int newDimension = matrix.length / 2;
int[][] toReturn = new int[newDimension][newDimension];
for (int i = 0; i < newDimension; i++) {
for (int j = 0; j < newDimension; j++) {
toReturn[i][j] = matrix[i + newDimension][j + newDimension];
}
}
return toReturn;
}
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)
I am trying to implement in Eclipse Java Levenshtein distance on the following two strings:
I took the idea from Wikipedia, but I don't know why my output is wrong, I need help to find my mistake/s.
"kruskal"
"causal"
package il.ac.oranim.alg2016;
public class OPT {
public static void main(String[] args)
{
char[] t={'k','r','u','s','k','a','l'};
char[] s={'c','a','u','s','a','l'};
for (int i=0;i<=s.length;i++)
{
for (int j=0;j<=t.length;j++)
System.out.print(LevenshteinDistance(s,t)[i][j]+" ");
System.out.println();
}
}
private static int[][] LevenshteinDistance(char s[], char t[])
{
// d is a table with m+1 rows and n+1 columns
int[][] d=new int[s.length+1][t.length+1];
for (int i=0;i<=s.length;i++)
d[i][0] = i; // deletion
for (int j=0;j<=t.length;j++)
d[0][j] = j; // insertion
for (int j=1;j<t.length;j++)
{
for (int i=1;i<s.length;i++)
{
if (s[i] ==t[j])
d[i][j]=d[i-1][j-1];
else
d[i][j] = Math.min(Math.min((d[i-1][ j] + 1),
(d[i][j-1] + 1)),
(d[i-1][j-1] + 1)) ;
}
}
return d;
}
}
My output:
0 1 2 3 4 5 6 7
1 1 2 3 4 4 5 0
2 2 1 2 3 4 5 0
3 3 2 1 2 3 4 0
4 4 3 2 2 2 3 0
5 5 4 3 3 3 2 0
6 0 0 0 0 0 0 0
The output should be:
0 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 2 3 4 5 5 6
3 3 3 2 3 4 5 6
4 4 4 3 2 3 4 5
5 5 5 4 3 3 3 4
6 6 6 5 4 4 4 3
If you reread the specifications, you will find there are two errors:
on the wikipedia, they use indices ranging from 1 to (and including n), a string starts at index i=1 according to Wikipedia where it is i=0 in Java; and
the weights are not updated correctly:
if (s[i] ==t[j])
d[i][j]=d[i-1][j-1];
In the specifications, this should be the minimum of d[i-1][j]+1, d[i][j-1]+1 and d[i-1][j-1]. It is not guaranteed that d[i-1][j-1] is the lowest value, so you should effectively calculate it.
If one takes these mistakes into account, one can modify the table update algorithm (changes on comment //):
for (int j=1;j<=t.length;j++) { //use <= instead of <
for (int i=1;i<=s.length;i++) { //use <= instead of <
if (s[i-1] ==t[j-1]) //use i-1 and j-1
d[i][j] = Math.min(Math.min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]); //use the correct update
else
d[i][j] = Math.min(Math.min(d[i-1][j]+1,d[i][j-1]+1),d[i-1][j-1]+1);
}
}
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;
}
}
}
Before the Floyd–Warshall/Dijkstra replies flood comes in please let me explain the situation as i'm sure either algorithm can be tuned for this case, and it has to be as this is not a toy example program (mind you, in java so have to keep it manageable memory-wise)
What i have is a web graph generated from node 0 to node n, node 3 cannot link to node 5, because node 5 didnt exist when node 3 was choosing it's out links. Every "node" is represented as in_neighbours[nodeID] and out_neighbours[nodeID] say nodeId=3, so we're talking about node 3. Note also that in_/out_ are both sorted, (in_ is naturally sorted as 5 will have chosen its out links all at once, only then 6 will choose out_links so 3's in_'s can never contain {6, 5, 7}) and ofc both can contain duplicates. (in/out are ArrayList arrays of size n, where out_ is always of size d or m, which along with n is specified at startup by the user)
No weights. What i must do is find the averageDistance()
public double getAvgDistance() {
int sum = 0;
for (int i=1; i<n; i++) {
for (int j=0; j < i; j++) {
sum += dist(i, j); // there are duplicates, make sure i skip
}
}
return (double)sum / (double)( ((n*(n-1)) / 2) );
}
What I have so far is the best case. Note i want only to find the distance between j & i, not all distances at the same time (not enough memory, it will be tested at m=20 d=1 000 000)
private int dist(int i, int j) {
int dist = 0;
for (int link : in_neighbours[j]) {
System.out.print("\nIs "+j+" linked to by "+i);
if (out_neighbours[i].contains(link)) {
System.out.print(" - yes!");
dist = 1;
}
}
return dist;
}
So im asking if the "fresher" (ofc at this point the graph is completed) node i is linking to any of its older buddies directly if so, distance is 1 hop.
Is it just me or the 'shortest' path will always be the first found path if nodes are traversed backwards?
How do i check if its not 1, the "else" after the base case? My math is fairly weak please be gentle :)
Any hints how to make use of the fact that the links are sorted?
It's not homework or something that im trying to cheat around from, it's not about the code itself, this has to be a useful tool, the "learning" comes by itself along the way.
here's how a graph looks nodeID, out links, in links for m=7 n=13, (note the 0 cycles is just how the graph is initialized):
0 | 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 1 1 1 1 1 1 1 2 2 2 2 2 3 4 5 6 6 7 8 9
1 | 0 0 0 0 0 0 0 | 2 2 3 4 5 5 8 12
2 | 0 0 0 0 0 1 1 | 3 3 3 3 3 4 4 4 6 7 8 10
3 | 0 1 2 2 2 2 2 | 4 4 5 5 6 6 7 11
4 | 0 1 2 2 2 3 3 | 5 5 6 8 9 10
5 | 0 1 1 3 3 4 4 | 6 7 8 9 9 11 12
6 | 0 0 2 3 3 4 5 | 7 7 7 8 9 9 12
7 | 0 2 3 5 6 6 6 | 8 9 10 11 11 12
8 | 0 1 2 4 5 6 7 | 10 10 10 11 12
9 | 0 4 5 5 6 6 7 | 10 11 11
10 | 2 4 7 8 8 8 9 | 12 12
11 | 3 5 7 7 8 9 9 |
12 | 1 5 6 7 8 10 10 |
Sorry for the agonising long read.
EDIT: Wrong code in the methods, this is what i think is correct now.
Revision of dist nr2, just try and find if theres a path at all:
private int dist(int i, int j) {
int dist = 0, c = 0, count = 0;
boolean linkExists = false;
for (int link : in_neighbours[j]) {
//System.out.print("\nIs "+j+" linked to by "+i);
if (out_neighbours[i].contains(link)) {
//System.out.print(" - yes!");
dist = 1; // there is a direct link
} else {
while ( c < j ) {
// if there's a path from 0 up to j, check if 'i' links to a node which eventually links to 'j'
if (out_neighbours[i].contains(c) &&
(out_neighbours[c].contains(link) || in_neighbours[c].contains(link) )) {
count++; // yes. and this is one node we had to step through to get closer
linkExists = true;
} else {
linkExists = false; // unreachable, the path was interrupted somewhere on the way
break;
}
c++;
}
if (linkExists) {
dist = count-1; // as 2 nodes are linked with 1 edge
} else {
dist = 0; // no path was found
}
}
}
return dist;
}
Since all edges have the same weight in your model, you can use a BFS search to find the shortest path from S to T.
This is an iterative process, starting with set #0, containing only the source node ({S}).
At each step i, you create set #i by finding all nodes achievable from set (i-1) in one step.
The iteration terminates in two cases:
1) When you detect that set #k contains T. In this case you return k-1.
2) When the set is empty, meaning that the two nodes are unreachable.
The memory consumption is about twice the number of nodes, since at each step i you are working with two sets (i-1 and i), bounded by the total number of nodes.
--EDIT--
Here is a possible implementation (I made some tests on it):
private Integer getDist(int i, int j) {
Set<Integer> currentSet = new HashSet<Integer>();
currentSet.add(i);
int dist = 0;
while (true) {
Set<Integer> nextSet = new HashSet<Integer>();
for (Integer currNode : currentSet)
nextSet.addAll(out[currNode]);
if (nextSet.isEmpty())
return null; //i.e. infinite
if (nextSet.contains(j))
return dist;
dist++;
currentSet = nextSet;
}
}
The implementation assumes that in and out are defined as List<Integer>[], and nodes are identified by numbers starting from 0. The minimal distance is counted as the number of intermediate nodes in the path, and not as the number of edges.
The duplicates you have in the lists do not break anything here, but they are irrelevant for the algorithm.