Thread: Binary Search and Bubble Sort help

1. Binary Search and Bubble Sort help

Code:
```

//Could someone please tell me is my fill an array function and bubble sort function wrong or correct, because when you compile this code the integers are sorted from 1 to 100, but some of them are repeated twice for the same index, why is that?

#include<stdio.h>
#include<stdlib.h>
void fillArray ( int grades [] );
main()

{

int

key;

system("pause");

}
void fillArray ( int grades [] )
{
int array [100];
int i;

for ( i= 0; i < 100;i ++)
{
grades[i] = rand() % 100 + 1;
}
}
{
int i;

for(i =0;i < 100;i++)

{

}

}

{
int i , x;
int temp;

for ( x=0; x<100; x++)
{
for ( i=0; i<100 ; i++)
{
{
}
}
}

}

{
int

i,

start,

end,

middle;

for (start = 0, end = 100-1; start <= end;)
{
printf ("\nEnter the number you are looking for: ");
scanf ("%d",&i);
middle= start+(end-start) / 2;
}
{
end = middle - 1;
}
{
start = middle + 1;

}

else
{
return middle;

}

return -1;

}```

2. grades[i+1] overflowed when i == 99

What exactly do you mean by grades[i+1] overflowed when i == 99. In other words how do I fix the problem if you know.

4. Originally Posted by IMMORTALX
What exactly do you mean by grades[i+1] overflowed when i == 99. In other words how do I fix the problem if you know.
Is i+1 part of your inner sorting loop? Yes.

When i equals 99 what is i+1? Clearly, 100. That's cutting edge arithmetic, I know, and unknown stuff in our government, but I hope you can do better than our politicians.

Is array[100] part of an array with 100 elements? No, array indices would be 0 through 99 only.

You always have to watch out for indices or pointers, that they don't run past their boundaries. It's on the edges where we have to be much more careful.

5. In your bubble sort function, where you applied nested loops...
In outer loop, run your loop, <99 not <100.
In inner loop, initialize everytime your inner loop with the outer loop variable and run it <100.

6. Array help

Code:
```//This is my new code,but I still have the same problem.  When you compile this code the integers are sorted from 1 to 100, but some of them are repeated twice for the same index, why is that?

#include<stdio.h>
#include<stdlib.h>
void fillArray ( int grades [] );
main()

{

int

key;

system("pause");

}
void fillArray ( int grades [] )
{
int array [100];
int i;

for ( i= 0; i < 100;i ++)
{
grades[i] = rand() % 100 + 1;
}
}
{
int i;

for(i =0;i < 100;i++)

{

}

}

{
int

x,

i,

t;

for(x=1;x<100;x++)

for(i=100-1;i>=x;i--)

{
{

}
}

}

{
int

i,

start,

end,

integers,
middle;

for (start = 0, end = 100-1; start <= end;)
{

middle= start+(end-start) / 2;
printf ("\nEnter the number you re looking for");
scanf ("%d",&i);
}
{
end = middle - 1;
}
{
start = middle + 1;

}

else

{

return middle;

}

return -1;

}```

7. There are some problems with the code:

1) In the binary search, it's not horrid, but this for loop is has too many tests for it's stop. Start and stop indices will ALWAYS cross at the right times, for your loop. So it's an added test to the binary search loop, that is unnecessary.

2) When you get random numbers, you can expect to have some repeated values - otherwise, it's not random. Maybe you want UNIQUE random numbers? That can be done, but that's not what the program is doing, currently.

3) Why the scanf() in the middle of the binary search? That's not how it works. You ask for the number to be searched for OUTSIDE the search loop or function - not inside it.

8. Originally Posted by IMMORTALX
[code]

//This is my new code,but I still have the same problem. When you compile this code the integers are sorted from 1 to 100, but some of them are repeated twice for the same index, why is that?
Because you are filling the array with random numbers which are probably repeating. If you take 100 random numbers from 1 to 100 it is very likely you will get several repeats in the sequence...

Your sort may be working just fine... the way to test it is to fill the array with known values.

Code:
```void fillArray ( int grades [] )
{
int array [100];
int i;
for ( i= 0; i < 100;i ++)
{
grades[i] = rand() % 100 + 1;
}
}```

9. I don't get a large straight every time I play yahtzee, so you shouldn't expect to get all 1-100.
This isn't used:
Code:
`   int array [100];`
And your code formatting is terrible.

Turn your warning level up and pay attention to what they tell you.

10. Code:
```TEST #2 on arrays

Write a C program that asks the user to enter a series of integers. Your program is supposed to display the largest, the second largest, and also displays the number of integers that are less than the average of those entered integers.

Sample execution (in bold is the user’s entry):

Enter how many integers do you have (up to 10): 5
Enter your integers:  2 5 76 9 90

You entered the following numbers:
2
5
76
9
90

And you have:
-	Largest 90
-	Second largest 76
-	There are  3 integers that are less than the average

You will need to have a function for each of the following tasks:

1)	Find largest-use the prototype int large ( int array[] );
This function takes the array of integers and returns its largest element

2)	Find the second largest: int secondLarge ( int array[] );

3)	double average ( int array[]);
This returns the average of the array

4)	void printArray ( int array ); to print the array’s element

Feel free to add more functions if you see fit.

// I need help programmig this problem.
Especially with finding the largest, second largest,
and average of the array.
Also, in my print array function,
I am trying to get all the integers to print out that the user enters in a list,
but while not repeating the printf("\n\nYou entered the following numbers\n\n".
So, I am having trouble with this code in my program

printf("\n\nYou entered the following numbers\n\n");

printf("%d",array[i]);

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int large(int array[]);
int secondLarge(int array[]);
double average(int array[]);
void printArray(int array[]);

main()
{
int array[SIZE]={0};

int

largest,

secondLargest,

arrayAverage;

largest = large(array);

secondLargest = secondLarge(array);

arrayAverage = average(array);

printArray(array);

system("pause");

}
//-------------------------
int large (int array[])
{

int

largest = SIZE -1,

i;

for(i=0;i<SIZE;i++);
{
return largest;

}
}
//------------------------
int secondLarge ( int array[])
{

int

secondLargest = SIZE -2,

i;

for(i=0;i<SIZE;i++);
{
return secondLargest;

}

}
//-------------------------
double average(int array[])
{
int

arrayAverage,

i;

for(i=0;i<SIZE;i++);
{
arrayAverage = array[i] / 2;

return arrayAverage;

}

}
//-------------------------
void printArray(int array[])
{

int

arrayAverage,

largest,

secondLargest,

integers,

i;

printf("Enter how many integers do you have (up to 10):\n");

scanf("%d",&integers);

for(i=0;i<SIZE;i++)
{

scanf("%d",&array[i]);

printf("\n\nYou entered the following numbers\n\n");

printf("%d",array[i]);

}

printf("\n\nAnd you have\n\n");

printf("- Largest %d\n",largest);

printf("- Second largest %d\n",secondLargest);

if ( array[i] <  arrayAverage)
{
printf("\n- There are 3 integers that are less than the average,%d",array[i]);
}

}```
\\ I need extremely good help programming this is critical its my final exam I on the verge of failing the class.

Code:
```The purpose of this assignment is to create a fee invoice application for students attending Valence Community College. The main menu for your application must have the following options.

2- Add/Delete a course for a student
3- Search for a student
4- Print fee invoice
5- Print fee invoice sorted by crn
Etc…

For every option, you must have a separate function. Feel free to add helper functions as needed.

It costs 120.25 dollars per credit hour in addition to \$35.00 charged for health and id services.

Valence Community College offers the following course:

CRN		Course 			Credit Hours
4587		MAT 236			4
4599		COP 220			3
8997		GOL 124			1
9696		COP 100			3

Note that we are considering the names of the students in this project.

As a first step, you need to decide which data structure(s) you will use to store the students’ data.
A fee invoice should look like

VALENCE COMMUNITY COLLEGE
ORLANDO FL 10101
---------------------

Fee Invoice Prepared for Student:
5959-DANIEL TAZI

1 Credit Hour = \$120.25

CRN	CR_PREFIX	CR_HOURS
4599	COP 220		3\$ 360.75
4587        MAT 236		4\$ 481.00

Health & id fees	                  \$  35.00

---------------------------------------------------------------
Total Payments	                  \$  876.75

Sample Run (The user’s entry is in bold)

Welcome!
Choose from the following options:
3- Search for a student
4- Print fee invoice
5- Print fee invoice sorted by crn
0- Exit program

Enter the student’s id: 8989

No Student found!

<< Clear Screen >>

Choose from the following options:
3- Search for a student
4- Print fee invoice
5- Print fee invoice sorted by crn
0- Exit program

Enter the students’ id: 5959
Sorry, 5659 is already assigned to another student

Enter the student’s id: 5900
Enter student’s name: John Smith

Enter how many courses John Smith is taking?
2

Enter the 2 course numbers
4587	4599

Press Any Key To Continue. . .
<< Clear Screen >>

Choose from the following options:
3- Search for a student
4- Print fee invoice
5- Print fee invoice sorted by crn
0- Exit program

Enter the student’s id: 5959

<< Clear Screen >>

VALENCE COMMUNITY COLLEGE
ORLANDO FL 10101
-------------------------------
Fee Invoice Prepared for Student:
5959-DANIEL TAZI

1 Credit Hour = \$120.25

CRN	CR_PREFIX	CR_HOURS
4587        MAT 236		4	\$ 481.00
4599	COP 220		3	\$ 360.75

Health & id fees	                                \$  35.00

-------------------------------------------------------------
Total Payments	                                \$ 876.75

Press Any Key To Continue. . .
<< Clear Screen >>

Choose from the following options:
3- Search for a student
4- Print fee invoice
5- Print fee invoice sorted by crn
0- Exit program

Enter the student’s id: 5959

Here are the courses [DANIEL TAZI] is taking:
CRN	PREFIX		CR. HOURS
4587	 MAT 236		4
4599	COP 220		3

Choose from:
A- Add a new course for [DANIEL TAZI]
D- Delete a course from [DANIEL TAZI]’s schedule
C- Cancel operation

Enter course Number to delete: 4599

[4599	COP 220] is deleted successfully!

Want to display new invoice? Y/N: y

<< Clear Screen >>

VALENCE COMMUNITY COLLEGE
ORLANDO FL 10101
---------------------

Fee Invoice Prepared for Student:
5959-Daniel Tazi

1 Credit Hour = \$120.25

CRN	CR_PREFIX	CR_HOURS
4588	 MAT 236		4	\$ 481.00

Health & id fees	                                \$  35.00

----------------------------------------------------------------
Total Payments	                                \$  516.00

Press Any Key To Continue…
<< Clear Screen >>

Choose from the following options:
3- Search for a student
4- Print fee invoice
5- Print fee invoice sorted by crn
0- Exit program

Goodbye!```

11. You already know the logic for this first problem "find largest", you just need to discover that.

If someone tasked you with finding the biggest apple in a bunch of apples, you'd have no problem with it. You'd pick up the apples, or look at them, one by one, and compare their sizes.

Same thing here - just using C to do it.

Code:
```//-------------------------
int large (int array[])
{
/* make largest the first apple you pick up, and generally, humans prefer to
work from lower to higher indices */
int largest = array[0];  //the lowest index in the array
int i;
/* use no semi-colon on the first line of a loop statement with more than one line */
for(i=0;i<SIZE;i++) //SIZE is a #defined value
{
if(array[i] > largest) //do we have a new largest now?
largest = array[i]; //if so, make it our new largest value

}

/* all the numbers have been compared, and the largest has been found,
so return it */
return largest;
}```
Second largest is a bit trickier, but not much. The logic could be:

Take the first number in the array, into the largest variable, like before. Now go through the array. According to the assignment, you can't use the largest value that you found in the largest function, here. You have to find it all over again.

Every time you find a new largest value, the old largest value will become the new second largest value. It's a "hand me down" value, for second_largest:

Just as largest variable isn't always equal to array[SIZE]-1, secondLargest has nothing to do with being equal to array[SIZE]-2. Don't make that assignment!

Code:
```//start of for loop
if(array[i] > largest) {
second_largest = largest;
largest = array[i];
}
//end of for loop

return second_largest;```
To find the mean, you'll add up all the numbers in the array, again using a for loop,
and then after the for loop, you'll divide that sum by how many numbers you added up.

Give that a try!

12. Is this program correct that I wrote, especialy with the search and bubble sort.

Code:
```#include<stdio.h>
#include<stdlib.h>
void fillArray ( int grades [] );
main()

{

system("pause");

}

//-----------------------------------
void fillArray ( int grades [] )
{

int i;

for ( i= 0; i < 100;i++)
{
grades[i] = rand() % 100 + 1;
}
}

//--------------------------------------
{
int i;

for(i =0;i < 100;i++)

{

}

}

//--------------------------------------------

{
int i, check, temp = 0;

for(i = 0; i <100; i++)
{    for(check = 0; check < 100-1; check++)

}
}
}

}
{
int first,last,mid,found,target,i,before, after, locBefore, locAfter;
first = 0;
last = 100- 1;

printf("\n\tEnter a number: ");
scanf("%d", &target);

while(first <= last && found!=1 )
{
mid = (first + last)/2;
{
found = 1;
}
first = mid+1;
last = mid - 1;
else
first = last +1;
}

if (found == 1)
{

printf("\n\n\t%d was found at location %d \n\n", grades[mid], mid);
}

else
{
printf("\n\t%d was not found at any of the array locations \n\n", target);

before = 0;
after = 100;
for(i = 0; i < 100; i++){
locBefore = i;
}
locAfter = i;
}

}
}

}```
Code:
```#include<stdio.h>
#include<stdlib.h>
main()

{

int i;

system("pause");

}

//------------------------------------

{
int

i;

for(i =0;i < 5;i++)

{

}

}

//-------------------------------------------
{
int i, check, temp = 0;

for(i = 0; i <5; i++)
{    for(check = 0; check < 5-1; check++)

}
}
}

}

//-----------------------------------------
{
int i, query, result = -1;
printf("\nEnter a number: ");
scanf("%d", &query);

for(i = 0; i < 5; i++){
{
result = i;
}

}
if(result!=-1)
printf("\n\n\t%d was found at location %i in the array.\n\n\n ",query, result);
else
{
}
}```

13. Code:
```I am trying to write a code that allows the user to in put up to 10 integers in the array, please
look at the last function of my program and tell me what I am doing wrong,Thanks.  I am also having trouble finding the largest and second largest of the integers of the array.  Also, I am having trouble finding the average of the array and displaying the 3 integers that are less than the average.

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int large(int array[]);
int secondLarge(int array[]);
double average(int array[]);
void printArray (int array[]);
void printExecution(int array[]);

main()
{
int array[SIZE]={0};

int

largest,

secondLargest,

arrayAverage;

largest = large(array);

secondLargest = secondLarge(array);

arrayAverage = average(array);

printExecution(array);

system("pause");

}
//-------------------------
int large (int array[])
{

int

largest = array[0],

i;

for(i=0;i<SIZE;i++);
{
if(array[i] > largest)
{
largest = array[i];
return largest;
}

}
}
//------------------------
int secondLarge ( int array[])
{

int

secondLargest = SIZE -2,

i;

for(i=0;i<SIZE;i++);
{
return secondLargest;

}

}
//-------------------------
double average(int array[])
{
int

arrayAverage,

i;

for(i=0;i<SIZE;i++);
{
arrayAverage = array[i] / 2;

return arrayAverage;

}

}
//-------------------------
void printArray (int array[])
{
int

i;

printf("\n\nYou entered the following numbers\n\n");

for(i=0;i<SIZE;i++)

{

printf("%d",array[i]);

}

}
void printExecution(int array[])
{

int

arrayAverage,

largest,

i,

secondLargest,

integers;

printf("Enter how many integers do you have (up to 10):\n");

scanf("%d",&array[i]);

scanf("%d",&array[i]);

printArray(array);

printf("\n\nAnd you have\n\n");

printf("- Largest %d\n",largest);

printf("- Second largest %d\n",secondLargest);

if ( array[i] <  arrayAverage)
{
printf("\n- There are 3 integers that are less than the average,%d",array[i]);
}

}```

14. You can't return the largest (or smallest, or whatever), until AFTER the loops have finished going through all the values in the array.

So drop the return down, to where it's out of the loops. That should be the last statement in your function.