Skip to content

Instantly share code, notes, and snippets.

@timxor
Created May 5, 2017 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timxor/23aac523ffe5bd07afe0ef2851d16ae6 to your computer and use it in GitHub Desktop.
Save timxor/23aac523ffe5bd07afe0ef2851d16ae6 to your computer and use it in GitHub Desktop.
SSTF
int SSTF(int start_index, int a[]) {
/*
START INITILIZATION
*/
int distance = 0;
int counter_limit = 0;
int current_value = a[start_index];
int current_index = start_index;
// keep track of visited locations
int already_visited[1001];
int right_value = -1;
int left_value = -1;
int right_index = -1;
int left_index = -1;
for (int i = 0; i < 1001; ++i) {
already_visited[i] = 0;
}
//mark first address as visited
already_visited[current_index] = 1;
/*
END INITILIZATION
*/
/*
START LOOP
*/
while(counter_limit < 1001){
// get right index, check bounds first
if ((start_index - 1) > 0) {
// in bounds
right_index = (start_index - 1);
} else{
// out of bounds
right_index = -1;
}
// get left index, check bounds first
if ((start_index + 1) < 1001)
{
left_index = (start_index + 1);
} else{
left_index = -1;
}
// if left and right are within bounds
if(right_index != -1 && left_index != -1)
{
left_value = a[left_index];
right_value = a[right_index];
int left_distance = abs((current_value - left_value));
int right_distance = abs(current_value - right_value));
// if the left value is closer
if (left_distance < right_distance) {
// update distance
distance += left_distance;
already_visited[left_index] = 1;
current_index = left_index;
} else { // if the right value is closer
// update distance
distance += right_distance;
// mark visited
already_visited[right_index] = 1;
current_index = right_index;
}
}else if(right_index != -1)
{
right_value = a[right_index];
// update distance
distance += right_distance;
// mark visited
already_visited[right_index] = 1;
current_index = right_index;
}
else if(left_index != -1)
{
left_value_value = a[left_index];
// update distance
distance += left_distance;
// mark visited
already_visited[left_index] = 1;
current_index = left_index;
}
else{
printf("Hmmmm this should not be hit? \n");
}
// increment counter_limit
counter_limit++;
}
/*
END LOOP
*/
return distance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment