void InsertSort(vector
<int> &arr
){
for(int i
= 1;i
< arr
.size();++i
){
for(int j
= i
;j
> 0;--j
){
if(arr
[j
] < arr
[j
- 1]){
int temp
= arr
[j
];
arr
[j
] = arr
[j
-1];
arr
[j
-1] = temp
;
}
else break;
}
}
}
void BubbleSort1(vector
<int> &arr
){
for (int i
= 0; i
< arr
.size() - 1; i
++) {
bool flag
=true
;
for (int j
= 0; j
< arr
.size() - i
- 1; j
++) {
if (arr
[j
] > arr
[j
+ 1]) {
int temp
= arr
[j
];
arr
[j
] = arr
[j
+ 1];
arr
[j
+ 1] = temp
;
flag
=false
;
}
}
if(flag
) return;
}
}
void BubbleSort2(vector
<int> &arr
){
for (int i
= 0; i
< arr
.size() - 1; i
++) {
bool flag
=true
;
for (int j
= arr
.size()-1; j
> i
; j
--) {
if (arr
[j
] < arr
[j
- 1]) {
int temp
= arr
[j
];
arr
[j
] = arr
[j
+ 1];
arr
[j
+ 1] = temp
;
flag
=false
;
}
}
if(flag
) return;
}
}
void quicksort(vector
<int> &arr
, int left
, int right
)
{
if(left
>= right
) return ;
int i
= left
;
int j
= right
;
int key
= arr
[left
];
while(i
< j
)
{
while(i
< j
&& key
<= a
[j
])
{
j
--;
}
arr
[i
] = arr
[j
];
while(i
< j
&& key
>= a
[i
])
{
i
++;
}
arr
[j
] = arr
[i
];
}
arr
[i
] = key
;
quicksort(arr
, left
, i
- 1);
quicksort(arr
, i
+ 1, right
);
}
void Merge(int* a
, int* b
, int start
, int end
)
{
if (start
>= end
) return;
int mid
= (start
+ end
) >> 1;
int start1
= start
,end1
= mid
;
int start2
= mid
+ 1, end2
= end
;
Merge(a
, b
, start1
, end1
);
Merge(a
, b
, start2
, end2
);
int k
= start
;
while (start1
<= end1
&& start2
<= end2
)
b
[k
++] = a
[start1
] < a
[start2
] ? a
[start1
++] : a
[start2
++];
while (start1
<= end1
)
{
b
[k
++] = a
[start1
++];
}
while (start2
<= end2
)
{
b
[k
++] = a
[start2
++];
}
for (k
= start
;k
<= end
;k
++)
a
[k
] = b
[k
];
}
void MergeSort(int *a
,int *b
,int len
)
{
Merge(a
, b
, 0, len
- 1);
}
void Shellsort(int a
[], int len
){
int gap
=len
-1;
bool flag
=0;
while(gap
>=1){
if(gap
==1) flag
=1;
for(int i
=0;i
<len
;i
++){
if(i
+gap
<len
){
if(a
[i
]>a
[i
+gap
]){
int temp
=a
[i
];
a
[i
]=a
[i
+gap
];
a
[i
+gap
]=temp
;
}
}
else break;
}
gap
=gap
/3+1;
if(flag
) break;
}
}
void HeapSort(int arr
[],int len
){
int i
;
for(i
= len
/2 - 1; i
>= 0; --i
){
Heapify(arr
,i
,len
);
}
for(i
= len
- 1;i
> 0;--i
){
int temp
= arr
[i
];
arr
[i
] = arr
[0];
arr
[0] = temp
;
Heapify(arr
,0,i
);
}
}
void Heapify(int arr
[], int first
, int end
){
int father
= first
;
int son
= father
* 2 + 1;
while(son
< end
){
if(son
+ 1 < end
&& arr
[son
] < arr
[son
+1]) ++son
;
if(arr
[father
] > arr
[son
]) break;
else {
int temp
= arr
[father
];
arr
[father
] = arr
[son
];
arr
[son
] = temp
;
father
= son
;
son
= 2 * father
+ 1;
}
}
}
转载请注明原文地址:https://tech.qufami.com/read-19700.html