I need to sort book objects by their titles in a simple way. However, the selection sort algorithm I wrote isn't working properly and just moves the books around, but with no apparent order. What am I doing wrong?
int j;
int b;
for (int i = 0; i < 20 - 1; i++) {
int minIndex = i;
for (j = i + 1; j < 20; j++) {
b = (bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if (b < 0) {
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[j];
bookA[j] = temp;
}
for (int z = 0; z < 20; z++)
System.out.println(bookA[z].toString());
You're using j as an index in bookA[i] = bookA[j];. The problem is that you're overriding the value of j at every iteration, so when it finally gets to bookA[i] = bookA[j]; it will always be 20.
What you want is to replace it with bookA[minIndex]. The resulting code would look like this:
int j;
int b;
for(int i=0;i<20-1;i++){
int minIndex=i;
for(j=i+1;j<20; j++) {
b=(bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
if(b<0){
minIndex=j;
}
}
Book temp = bookA[i];
bookA[i] = bookA[minIndex];
bookA[minIndex] = temp;
}
for(int z=0;z<20;z++)
System.out.println(bookA[z].toString());
Related
I've been trying to tackle this bug for a while, but I can't get around to it. The purpose of the program below is to use bubble sort to alphabetically order an array of names. For example, if the names are ["Bob Joe", "Bob Frank", and "Bob Johnson"], the correctly sorted array would be ["Bob Frank", "Bob Joe", "Bob Johnson"].
The main challenge I am having is comparing any 2 strings past name.charAt(0). If I only compare the characters of any 2 strings at 1 specific index point, my code works. However, if I try to make the comparison move past index 0 if index 0 of both strings are equal to each other, my program no longer works.
The code is outlined below
public static void sortAlpha (String names[])
{
for (int i = 0 ; i < names.length - 1 ; i++)
{
for (int a = 0 ; a < names.length - 1 - i ; a++)
{
int length1 = names [a].length ();
int length2 = names [a + 1].length ();
int min = 1;
if (length1 > length2)
{
min = length2;
}
else
{
min = length1;
}
for (int b = 0 ; b < min ; b++)
{
if ((int) names [a].toLowerCase ().charAt (b) > (int) names [a + 1].toLowerCase ().charAt (b))
{
String tempName = names [a];
// sort:
names [a] = names [a + 1];
names [a + 1] = tempName;
break;
}
}
}
}
}
If I simply default the min value to 1, the code runs and does its intended job. However, if the min value stays dynamic, the program does not work. I'm trying to discern why this is so and what the fix is. Any help would be appreciated!
Check this out.
public static void sortAlpha(String names[]) {
for (int i = 0; i < names.length - 1; i++) {
for (int a = 0; a < names.length - 1 - i; a++) {
int lengthLeft = names[a].length();
int lengthRight = names[a + 1].length();
int minLength = lengthLeft > lengthRight ? lengthRight : lengthLeft;
for (int b = 0; b < minLength; b++) {
int letterLeft = (int) names[a].toLowerCase().charAt(b);
int letterRight = (int) names[a + 1].toLowerCase().charAt(b);
if (letterLeft > letterRight) {
String tempName = names[a];
// sort:
names[a] = names[a + 1];
names[a + 1] = tempName;
break;
} else if (letterLeft == letterRight) {
// if the letters are the same go for the next letters
continue;
} else {
// if it's already in the right position - stop.
break;
}
}
}
}
}
Use this
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
You can simply use compareTo() and a temp variable to compare and store
Scanner sc = new Scanner(System.in);
String n[]= new String[5];
System.out.println("Enter the String");
for(int k = 0;k<5;k++) {
n[k] = sc.nextLine();
}
String temp;
System.out.println("sorted order:");
for (int j = 0; j < n.length; j++) {
for (int i = j + 1; i < n.length; i++) {
if (n[i].compareTo(n[j]) < 0) {
temp = n[j];
n[j] = n[i];
n[i] = temp;
}
}
System.out.println(n[j]);
I want to get a number from user and calculate how many different triangles can be formed with the given length for example :
5 (2-2-1)
Answer: 1
12 (5,5,2)(3,4,5)(4,4,4)
Answer: 3
I've wrote some codes but I want a faster way to do that.
Here is my codes:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
int value = 0;
for (int i = 1; i < t; i++) {
for (int j = i; j < t; j++) {
for (int h = j; h < t; h++) {
if (i+h+j == t & i+j > h & i+h > j & h+j > i) value++;
}
}
}
System.out.println(value);
}
You can do it in O(1):
int n = input.nextInt();
long value = Math.round(((long)n*n)/12d) - ((long)n/4)*(((long)n + 2)/4);
using Alcuin's Sequence.
You can make it O(n^2) easily.
for (int i = 1; i < t; i++) {
for (int j = i; j < t; j++) {
int h=t-i-j;
//check in O(1)
}
}
Two strings are given and we have to find the length of longest common substring. I don't know what's wrong with my code.
The outer loop takes a substring of B and the inner loop increases the substring by one character at a time.
For the input "www.lintcode.com code", "www.ninechapter.com code" the output is coming 5 but it should be 9
public class Solution {
/**
* #param A, B: Two string.
* #return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
int k = 0, temp = 0;
if(B.length() == 0){
return 0;
}
for(int i = 0; i < B.length()-1; i++){
String bb = B.substring(i, i+1);
if(A.contains(bb)){
for(int j = 1; j < A.length()-i; j++){
String bbb = B.substring(i, i+j);
if(!A.contains(bbb))
break;
temp = bbb.length();
}
}
if(temp > k)
k = temp;
}
return k;
}
}
Just replace this:
for(int j = 1; j < A.length()-i; j++)
with this:
for(int j = 1; j < B.length()-i+1; j++)
I believe you could reduce your function size a little with this...not sure if your method is more efficient or not though...
public int longestCommonSubstring(String A, String B) {
int longestSubstring = 0;
for (int x=0; x < A.length(); x++) {
for (int y=x; y < A.length() + 1; y++) {
String testString = A.substring(x,y);
if (B.contains(testString) && (testString.length() > longestSubstring)) {
longestSubstring = testString.length();
}
}
}
return longestSubstring;
}
It's a simple matter of flipping an image horizontally and/or vertically. The premise is that given a 2D integer array that was created from importing a picture, I must create a method with a int[][] param and horizontally flip it before returning void.
The syntax is below:
public static void horizontalFlip(int[][] imgArray)
{
int temp;
for (int i = 0; i < imgArray.length; i++)
{
for (int j = 0; j < imgArray[i].length / 2; j++)
{
temp = imgArray[i][j];
imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
imgArray[imgArray.length - 1 - i][j] = temp;
}
}
}
I use imgArray as the array param and use temp as a placeholder while the loop swaps pixels, or rather, that was the intention. Currently the window does nothing after prompting the flip. Can somebody help me find the problem with the logic or syntax?
Thanks in advance, please specify any details I should provide
P.S. I can confirm the unreferenced supplied code is functional and tested.
It is happening because you are using i instead of j. But i will not stop after halfway, but it is continued and re-swap the array.
Here is a correct code :
for (int i = 0; i < imgArray.length; i++) {
for (int j = 0; j < imgArray[i].length / 2; j++) {
temp = imgArray[i][j];
imgArray[i][j] = imgArray[i][imgArray.length - 1 - j];
imgArray[i][imgArray.length - 1 -j] = temp;
}
}
Or if you want to swap columns, not rows :
for (int i = 0; i < imgArray.length / 2; i++) {
for (int j = 0; j < imgArray[i].length; j++) {
temp = imgArray[i][j];
imgArray[i][j] = imgArray[imgArray.length - 1 - i][j];
imgArray[imgArray.length - 1 -i][j] = temp;
}
}
This will correctly flip the image horizontally:
public static void horizontalFlip(int[][] imgArray)
{
int temp;
for (int i = 0; i < imgArray.length; i++) {
for (int j = 0; j < imgArray[i].length/2; j++) {
temp = imgArray[i][j];
imgArray[i][j] = imgArray[i][imgArray[i].length - 1 - j];
imgArray[i][imgArray[i].length - 1 - j] = temp;
}
}
}
Please see my solution below,
for(int i=0; i<matrix.length / 2; i++)
{
int[] row = matrix[i];
int[] temp = row;
matrix[i] = matrix[matrix.length - 1];
matrix[matrix.length - 1] = row;
}
I need to write an algorithm that will take an array of ints and find the k'th largest element in the array. The caveat here is that the runtime must be O(K*n) or better.
My teacher has made it clear this can be done with a modified bubble sort program, but I am unsure as to how I can modify the bubble sort without ruining it, as I would think it necessary to loop through every element of the array. Here is my code (just the shell of the program and an unmodified bubble sort):
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
}
}
}
return sorted[k-1];
}
Figured it out:
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = 0; i < A.length-1; i++)
{
for (int j = 0; j < A.length-i-1; j++)
{
if (sorted[j] > sorted[j+1])
{
temp = sorted[j];
sorted[j] = sorted[j+1];
sorted[j+1] = temp;
}
if(i == (k-1)) return A[A.length-i-1];
}
}
return sorted[A.length-k];
}
The the array has been sorted to the k-th largest element, it has found what it is looking for and can stop the sort and return.
I thought a modified bubble sort just exited early if the list was already sorted?
Wouldn't something like this suffice?
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
bool bSorted = TRUE;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
bSorted = FALSE;
}
}
if(bSorted)
break;
}
return sorted[k-1];
}