मराठी
महाराष्ट्र राज्य शिक्षण मंडळएचएससी विज्ञान (संगणक विज्ञान) इयत्ता १२ वी

Write an algorithm for bubble sort with suitable example.

Advertisements
Advertisements

प्रश्न

Write an algorithm for bubble sort with suitable example.

सविस्तर उत्तर
Advertisements

उत्तर

Here, DATA is a linear array with N elements. This algorithm sorts the elements of DATA in ascending order.

Step 1: Repeat steps 2 and 3 for K = 1 to N – 1

Step 2: Set Ptr: = 1

Step 3: Repeat while Ptr ≤ N – K

  1. If DATA[Ptr] > DATA[Ptr + 1], then interchange DATA[Ptr] and DATA[Ptr + 1]
  2. Set Ptr := Ptr + 1

Step 4: Exit

After N – 1 passes, all elements are sorted.

Example:

Consider a linear array of 5 elements:

Data[1] = 55
Data[2] = 43
Data[3] = 05
Data[4] = 06
Data[5] = 09

Pass 1:
55 > 43 → swap → 43 55 5 6 9
55 > 5 → swap → 43 5 55 6 9
55 > 6 → swap → 43 5 6 55 9
55 > 9 → swap → 43 5 6 9 55

The largest element, 55, moves to the last position.

Pass 2:
43 > 5 → swap → 5 43 6 9 55
43 > 6 → swap → 5 6 43 9 55
43 > 9 → swap → 5 6 9 43 55

Second largest element 43 moves to the correct position.

Pass 3:
5 < 6 → no swap
6 < 9 → no swap

Final sorted list:
5 6 9 43 55

After N – 1 passes, the array is sorted in ascending order.

shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?

APPEARS IN

Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×