Presentation is loading. Please wait.

Presentation is loading. Please wait.

Similar presentations


Presentation on theme: ""— Presentation transcript:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57  max comparisons n n / 2 n / 2 n / 4 n / 4 … n / 4 n / 4 n / 4 n / 4n n / 2 n / 2n nn

58 FOR MERGE SORT, worstTime(n) IS O(n log n) THEREFORE averageTime(n) IS O(n log n)

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73 // Postcondition: a is in ascending order. The worstTime(n) is // O(n * n), and averageTime(n) is O(n log n). public static void sort (int[ ] a) { sort1(a, 0, a.length); } // method sort Quick Sort

74 // Postcondition: the array x, from index off (inclusive) to index // off + len (exclusive), is in ascending order. private static void sort1(int x[ ], int off, int len);

75 IF len < 7, USE INSERTION SORT OTHERWISE, PARTITION ABOUT A pivot ELEMENT

76 IF len = 7, pivot = x [off + len / 2] ; IF 7 < len <= 40, pivot = median of x [off], x [off + len / 2], x [off + len – 1] IF len > 40, SPLIT INTO 3 SEGMENTS, TAKE MEDIAN OF EACH SEGMENT; pivot = median of the 3 medians

77

78

79 int v = x[m];// v is the pivot int b = off, c = off + len - 1; while(true) { while (b <= c && x[b] <= v) b++; while (c >= b && x[c] >= v) c--; if (b > c) break; swap(x, b++, c--); } sort1 (x, off, c - off + 1); sort1 (x, b, len - b);

80

81

82

83

84

85

86

87

88 int v = x[m]; // Establish Invariant: v* ( v)* v* int a = off, b = a, c = off + len - 1, d = c; while(true) { while (b <= c && x[b] <= v) { if (x[b] == v) swap(x, a++, b); b++; } while (c >= b && x[c] >= v) { if (x[c] == v) swap(x, c, d--); c--; } if (b > c) break; swap(x, b++, c--); }

89

90

91

92

93

94

95

96

97

98

99

100


Download ppt ""

Similar presentations


Ads by Google