a. Bubble sort - Write a method called bubbleSort that takes as input, String []
ID: 3565980 • Letter: A
Question
a. Bubble sort - Write a method called bubbleSort that takes as input, String [] a, and sorts this array using bubbleSort. We define the number of comparisons as the number of times any entry is compared to an other one. In other words, this will be the number of time the method Compare is called in your code. Your bubble sort algorithm should follow this pseudo-code?3 and should return the number of comparisons made. Procedure bubbleSort (A) n = length (A) while not swapped swapped = false for i from 1 to n - 1 do if A[i-1] greater A[i] swap(A[i-1] , A[i]) swapped = true end if end for end while end procedureExplanation / Answer
int bubbleSort(string A){
bool swapped = false;
int compare = 0;
int n = strlen(A);
while(!swapped){
swapped = false;
for(int i=1; i<n-1;i++){
if(A[i-1]>A[i]){
swap(A[i-1],A[i]);
swapped = true;
}
compare++;
}
}
return compare;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.