• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How do “inner” and “outer” work in this bubble sort code?

Resolved: How do “inner” and “outer” work in this bubble sort code?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I am trying to learn the bubble sort algorithm in a book for C. I can’t seem to understand in the code below how int outer and int inner link to which element of the nums array. Like how does inner become nums[0] while outer becomes nums[1] (if I’m correct), then progresses through the loop?

#include
#include
#include

int main()
{
int ctr, inner, outer, didSwap, temp;
int nums[10];
time_t t;

srand(time(&t));

for (ctr = 0; ctr < 10; ctr++) { nums[ctr] = (rand() % 99) + 1; } puts("\n Here is the list before the sort: "); for (ctr = 0; ctr < 10; ctr++) { printf("%i\n", nums[ctr]); } for (outer = 0; outer < 9; outer++) { didSwap = 0; for (inner = outer; inner < 10; inner++) { if (nums[inner] < nums[outer]) { temp = nums[inner]; nums[inner] = nums[outer]; nums[outer] = temp; didSwap = 1; } } if (didSwap == 0) { break; } } puts("\n Here is the list after the sort: "); for ( ctr = 0; ctr < 10; ctr++) { printf("%i\n", nums[ctr]); } return 0; } [/code]

Answer:

inner never becomes nums[0]. inner and outer are array indexes, so when inner is 0, nums[inner] is nums[0].
The code that performs the comparison and swapping never does that with inner and outer, it uses nums[inner] and nums[outer].

if (nums[inner] < nums[outer]) { temp = nums[inner]; nums[inner] = nums[outer]; nums[outer] = temp; didSwap = 1; } [/code]

If you have better answer, please add a comment about this, thank you!

Share. Facebook Twitter LinkedIn

Related Posts

Resolved: itertools: cycle through several lists N times via iteration

24/03/2023

Resolved: Convert function is not working with {fn } in SQL Server

24/03/2023

Resolved: Why reference in pointer array doesn’t have data?

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.